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

4 years ago
5 years ago
4 years ago
5 years ago
5 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
4 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
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 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
4 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
3 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
5 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
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
4 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
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
5 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
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
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
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
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
3 years ago
3 years ago
4 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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "github.com/unknwon/i18n"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/modelarts"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/storage"
  28. "code.gitea.io/gitea/modules/util"
  29. )
  30. const (
  31. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  32. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  33. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  34. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  35. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  36. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  37. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  38. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  39. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  40. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  41. )
  42. var (
  43. gpuInfos *models.GpuInfos
  44. categories *models.Categories
  45. benchmarkTypes *models.BenchmarkTypes
  46. benchmarkGpuInfos *models.GpuInfos
  47. benchmarkResourceSpecs *models.ResourceSpecs
  48. trainGpuInfos *models.GpuInfos
  49. )
  50. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  51. const CLONE_FILE_PREFIX = "file:///"
  52. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  53. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  54. // MustEnableDataset check if repository enable internal cb
  55. func MustEnableCloudbrain(ctx *context.Context) {
  56. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  57. ctx.NotFound("MustEnableCloudbrain", nil)
  58. return
  59. }
  60. }
  61. func cutString(str string, lens int) string {
  62. if len(str) < lens {
  63. return str
  64. }
  65. return str[:lens]
  66. }
  67. func jobNamePrefixValid(s string) string {
  68. lowStr := strings.ToLower(s)
  69. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  70. removeSpecial := re.ReplaceAllString(lowStr, "")
  71. re = regexp.MustCompile(`^[_\\-]+`)
  72. return re.ReplaceAllString(removeSpecial, "")
  73. }
  74. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  75. ctx.Data["PageIsCloudBrain"] = true
  76. t := time.Now()
  77. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  78. ctx.Data["display_job_name"] = displayJobName
  79. result, err := cloudbrain.GetImages()
  80. if err != nil {
  81. ctx.Data["error"] = err.Error()
  82. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  83. }
  84. for i, payload := range result.Payload.ImageInfo {
  85. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  86. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  87. } else {
  88. result.Payload.ImageInfo[i].PlaceView = payload.Place
  89. }
  90. }
  91. ctx.Data["images"] = result.Payload.ImageInfo
  92. resultPublic, err := cloudbrain.GetPublicImages()
  93. if err != nil {
  94. ctx.Data["error"] = err.Error()
  95. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  96. }
  97. for i, payload := range resultPublic.Payload.ImageInfo {
  98. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  99. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  100. } else {
  101. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  102. }
  103. }
  104. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  105. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  106. if err != nil {
  107. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  108. return err
  109. }
  110. ctx.Data["attachments"] = attachs
  111. ctx.Data["command"] = cloudbrain.Command
  112. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  113. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  114. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  115. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  116. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  117. if categories == nil {
  118. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  119. }
  120. ctx.Data["benchmark_categories"] = categories.Category
  121. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  122. if gpuInfos == nil {
  123. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  124. }
  125. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  126. if trainGpuInfos == nil {
  127. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  128. }
  129. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  130. if benchmarkGpuInfos == nil {
  131. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  132. }
  133. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  134. if benchmarkResourceSpecs == nil {
  135. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  136. }
  137. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  138. if cloudbrain.ResourceSpecs == nil {
  139. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  140. }
  141. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  142. if cloudbrain.TrainResourceSpecs == nil {
  143. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  144. }
  145. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  146. ctx.Data["params"] = ""
  147. ctx.Data["branchName"] = ctx.Repo.BranchName
  148. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  149. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  150. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  151. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  152. ctx.Data["cloudbraintype"] = models.TypeCloudBrainOne
  153. return nil
  154. }
  155. func CloudBrainNew(ctx *context.Context) {
  156. err := cloudBrainNewDataPrepare(ctx)
  157. if err != nil {
  158. ctx.ServerError("get new cloudbrain info failed", err)
  159. return
  160. }
  161. ctx.HTML(200, tplCloudBrainNew)
  162. }
  163. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  164. ctx.Data["PageIsCloudBrain"] = true
  165. displayJobName := form.DisplayJobName
  166. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  167. image := form.Image
  168. uuid := form.Attachment
  169. jobType := form.JobType
  170. gpuQueue := form.GpuType
  171. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  172. resourceSpecId := form.ResourceSpecId
  173. branchName := form.BranchName
  174. repo := ctx.Repo.Repository
  175. tpl := tplCloudBrainNew
  176. command := cloudbrain.Command
  177. if jobType == string(models.JobTypeTrain) {
  178. tpl = tplCloudBrainTrainJobNew
  179. commandTrain, err := getTrainJobCommand(form)
  180. if err != nil {
  181. log.Error("getTrainJobCommand failed: %v", err)
  182. ctx.RenderWithErr(err.Error(), tpl, &form)
  183. return
  184. }
  185. command = commandTrain
  186. }
  187. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  188. if err == nil {
  189. if len(tasks) != 0 {
  190. log.Error("the job name did already exist", ctx.Data["MsgID"])
  191. cloudBrainNewDataPrepare(ctx)
  192. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  193. return
  194. }
  195. } else {
  196. if !models.IsErrJobNotExist(err) {
  197. log.Error("system error, %v", err, ctx.Data["MsgID"])
  198. cloudBrainNewDataPrepare(ctx)
  199. ctx.RenderWithErr("system error", tpl, &form)
  200. return
  201. }
  202. }
  203. if !jobNamePattern.MatchString(displayJobName) {
  204. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  205. return
  206. }
  207. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) && jobType != string(models.JobTypeTrain) {
  208. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  209. cloudBrainNewDataPrepare(ctx)
  210. ctx.RenderWithErr("jobtype error", tpl, &form)
  211. return
  212. }
  213. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  214. if err != nil {
  215. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  216. cloudBrainNewDataPrepare(ctx)
  217. ctx.RenderWithErr("system error", tpl, &form)
  218. return
  219. } else {
  220. if count >= 1 {
  221. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  222. cloudBrainNewDataPrepare(ctx)
  223. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  224. return
  225. }
  226. }
  227. if branchName == "" {
  228. branchName = cloudbrain.DefaultBranchName
  229. }
  230. downloadCode(repo, codePath, branchName)
  231. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  232. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  233. mkModelPath(modelPath)
  234. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  235. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  236. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  237. var gpuType string
  238. for _, gpuInfo := range gpuInfos.GpuInfo {
  239. if gpuInfo.Queue == gpuQueue {
  240. gpuType = gpuInfo.Value
  241. }
  242. }
  243. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  244. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  245. }
  246. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  247. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  248. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  249. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  250. }
  251. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  252. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  253. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  254. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  255. }
  256. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  257. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  258. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  259. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description, branchName, form.BootFile, form.Params,
  260. 0, 0, resourceSpecId)
  261. if err != nil {
  262. cloudBrainNewDataPrepare(ctx)
  263. ctx.RenderWithErr(err.Error(), tpl, &form)
  264. return
  265. }
  266. if jobType == string(models.JobTypeTrain) {
  267. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  268. } else {
  269. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  270. }
  271. }
  272. func CloudBrainRestart(ctx *context.Context) {
  273. var ID = ctx.Params(":id")
  274. var resultCode = "0"
  275. var errorMsg = ""
  276. var status = string(models.JobWaiting)
  277. task := ctx.Cloudbrain
  278. for {
  279. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  280. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  281. resultCode = "-1"
  282. errorMsg = "the job is not stopped"
  283. break
  284. }
  285. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  286. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  287. resultCode = "-1"
  288. errorMsg = "the job's version is too old and can not be restarted"
  289. break
  290. }
  291. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  292. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  293. resultCode = "-1"
  294. errorMsg = "you have no right to restart the job"
  295. break
  296. }
  297. var hasSameResource bool
  298. if gpuInfos == nil {
  299. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  300. }
  301. for _, resourceType := range gpuInfos.GpuInfo {
  302. if resourceType.Queue == task.GpuQueue {
  303. hasSameResource = true
  304. continue
  305. }
  306. }
  307. if !hasSameResource {
  308. log.Error("has no same resource, can not restart", ctx.Data["MsgID"])
  309. resultCode = "-1"
  310. errorMsg = "the job's version is too old and can not be restarted"
  311. break
  312. }
  313. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  314. if err != nil {
  315. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  316. resultCode = "-1"
  317. errorMsg = "system error"
  318. break
  319. } else {
  320. if count >= 1 {
  321. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  322. resultCode = "-1"
  323. errorMsg = "you have already a running or waiting task, can not create more"
  324. break
  325. }
  326. }
  327. err = cloudbrain.RestartTask(ctx, task, &ID)
  328. if err != nil {
  329. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  330. resultCode = "-1"
  331. errorMsg = "system error"
  332. break
  333. }
  334. break
  335. }
  336. ctx.JSON(200, map[string]string{
  337. "result_code": resultCode,
  338. "error_msg": errorMsg,
  339. "status": status,
  340. "id": ID,
  341. })
  342. }
  343. func CloudBrainBenchMarkShow(ctx *context.Context) {
  344. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  345. }
  346. func CloudBrainShow(ctx *context.Context) {
  347. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  348. }
  349. func CloudBrainTrainJobShow(ctx *context.Context) {
  350. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  351. }
  352. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  353. ctx.Data["PageIsCloudBrain"] = true
  354. debugListType := ctx.Query("debugListType")
  355. var task *models.Cloudbrain
  356. var err error
  357. if jobType == models.JobTypeTrain {
  358. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  359. } else {
  360. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  361. }
  362. if err != nil {
  363. log.Info("error:" + err.Error())
  364. ctx.Data["error"] = err.Error()
  365. return
  366. }
  367. result, err := cloudbrain.GetJob(task.JobID)
  368. if err != nil {
  369. log.Info("error:" + err.Error())
  370. ctx.Data["error"] = err.Error()
  371. return
  372. }
  373. if task.JobType == string(models.JobTypeTrain) {
  374. if cloudbrain.TrainResourceSpecs == nil {
  375. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  376. }
  377. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  378. if tmp.Id == task.ResourceSpecId {
  379. ctx.Data["GpuNum"] = tmp.GpuNum
  380. ctx.Data["CpuNum"] = tmp.CpuNum
  381. ctx.Data["MemMiB"] = tmp.MemMiB
  382. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  383. }
  384. }
  385. } else {
  386. if cloudbrain.ResourceSpecs == nil {
  387. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  388. }
  389. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  390. if tmp.Id == task.ResourceSpecId {
  391. ctx.Data["GpuNum"] = tmp.GpuNum
  392. ctx.Data["CpuNum"] = tmp.CpuNum
  393. ctx.Data["MemMiB"] = tmp.MemMiB
  394. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  395. }
  396. }
  397. }
  398. if result != nil {
  399. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  400. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  401. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  402. ctx.Data["resource_spec"] = spec
  403. if task.JobType == string(models.JobTypeTrain) {
  404. if trainGpuInfos == nil {
  405. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  406. }
  407. for _, resourceType := range trainGpuInfos.GpuInfo {
  408. if resourceType.Queue == jobRes.Config.GpuType {
  409. ctx.Data["resource_type"] = resourceType.Value
  410. }
  411. }
  412. } else {
  413. if gpuInfos == nil {
  414. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  415. }
  416. for _, resourceType := range gpuInfos.GpuInfo {
  417. if resourceType.Queue == jobRes.Config.GpuType {
  418. ctx.Data["resource_type"] = resourceType.Value
  419. }
  420. }
  421. }
  422. taskRoles := jobRes.TaskRoles
  423. if jobRes.JobStatus.State != string(models.JobFailed) {
  424. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  425. ctx.Data["taskRes"] = taskRes
  426. task.Status = taskRes.TaskStatuses[0].State
  427. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  428. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  429. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  430. if task.DeletedAt.IsZero() { //normal record
  431. err = models.UpdateJob(task)
  432. if err != nil {
  433. ctx.Data["error"] = err.Error()
  434. return
  435. }
  436. } else { //deleted record
  437. }
  438. } else {
  439. task.Status = jobRes.JobStatus.State
  440. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  441. {
  442. State: jobRes.JobStatus.State,
  443. },
  444. }}
  445. ctx.Data["taskRes"] = taskRes
  446. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  447. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  448. }
  449. ctx.Data["result"] = jobRes
  450. } else {
  451. log.Info("error:" + err.Error())
  452. return
  453. }
  454. user, err := models.GetUserByID(task.UserID)
  455. if err == nil {
  456. task.User = user
  457. }
  458. if task.BenchmarkTypeID > 0 {
  459. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  460. if task.BenchmarkTypeID == benchmarkType.Id {
  461. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  462. for _, benchmarkChildType := range benchmarkType.Second {
  463. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  464. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  465. break
  466. }
  467. }
  468. break
  469. }
  470. }
  471. }
  472. if task.TrainJobDuration == "" {
  473. if task.Duration == 0 {
  474. var duration int64
  475. if task.Status == string(models.JobRunning) {
  476. duration = time.Now().Unix() - int64(task.CreatedUnix)
  477. } else {
  478. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  479. }
  480. task.Duration = duration
  481. }
  482. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  483. }
  484. ctx.Data["duration"] = task.TrainJobDuration
  485. if len(task.Parameters) > 0 {
  486. var parameters models.Parameters
  487. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  488. if err != nil {
  489. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  490. task.Parameters = ""
  491. } else {
  492. if len(parameters.Parameter) > 0 {
  493. paramTemp := ""
  494. for _, Parameter := range parameters.Parameter {
  495. param := Parameter.Label + " = " + Parameter.Value + "; "
  496. paramTemp = paramTemp + param
  497. }
  498. task.Parameters = paramTemp[:len(paramTemp)-2]
  499. } else {
  500. task.Parameters = ""
  501. }
  502. }
  503. }
  504. attachment, err := models.GetAttachmentByUUID(task.Uuid)
  505. if err == nil {
  506. ctx.Data["datasetname"] = attachment.Name
  507. } else {
  508. ctx.Data["datasetname"] = ""
  509. }
  510. ctx.Data["task"] = task
  511. ctx.Data["jobName"] = task.JobName
  512. ctx.Data["displayJobName"] = task.DisplayJobName
  513. version_list_task := make([]*models.Cloudbrain, 0)
  514. version_list_task = append(version_list_task, task)
  515. ctx.Data["version_list_task"] = version_list_task
  516. ctx.Data["debugListType"] = debugListType
  517. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  518. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  519. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  520. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  521. ctx.Data["branchName"] = task.BranchName
  522. ctx.HTML(200, tpName)
  523. }
  524. func CloudBrainDebug(ctx *context.Context) {
  525. task := ctx.Cloudbrain
  526. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  527. ctx.Redirect(debugUrl)
  528. }
  529. func CloudBrainCommitImageShow(ctx *context.Context) {
  530. ctx.Data["PageIsCloudBrain"] = true
  531. ctx.Data["Type"] = ctx.Cloudbrain.Type
  532. ctx.HTML(200, tplCloudBrainImageSubmit)
  533. }
  534. func CloudBrainImageEdit(ctx *context.Context) {
  535. ctx.Data["PageIsImageEdit"] = true
  536. ctx.Data["PageFrom"] = ctx.Params(":from")
  537. var ID = ctx.Params(":id")
  538. id, err := strconv.ParseInt(ID, 10, 64)
  539. if err != nil {
  540. log.Error("GetImageByID failed:%v", err.Error())
  541. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  542. }
  543. image, err := models.GetImageByID(id)
  544. if err != nil {
  545. log.Error("GetImageByID failed:%v", err.Error())
  546. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  547. }
  548. ctx.Data["Image"] = image
  549. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  550. }
  551. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  552. if utf8.RuneCountInString(form.Description) > 255 {
  553. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  554. return
  555. }
  556. validTopics, errMessage := checkTopics(form.Topics)
  557. if errMessage != "" {
  558. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  559. return
  560. }
  561. image, err := models.GetImageByID(form.ID)
  562. if err != nil {
  563. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  564. }
  565. image.IsPrivate = form.IsPrivate
  566. image.Description = form.Description
  567. err = models.WithTx(func(ctx models.DBContext) error {
  568. if err := models.UpdateLocalImage(image); err != nil {
  569. return err
  570. }
  571. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  572. return err
  573. }
  574. return nil
  575. })
  576. if err != nil {
  577. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  578. } else {
  579. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  580. }
  581. }
  582. func CloudBrainImageDelete(ctx *context.Context) {
  583. var ID = ctx.Params(":id")
  584. id, err := strconv.ParseInt(ID, 10, 64)
  585. if err != nil {
  586. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  587. return
  588. }
  589. err = models.DeleteLocalImage(id)
  590. if err != nil {
  591. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  592. } else {
  593. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  594. }
  595. }
  596. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  597. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  598. if isExist {
  599. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  600. } else {
  601. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  602. }
  603. }
  604. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  605. if !NamePattern.MatchString(form.Tag) {
  606. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  607. return
  608. }
  609. if utf8.RuneCountInString(form.Description) > 255 {
  610. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  611. return
  612. }
  613. validTopics, errMessage := checkTopics(form.Topics)
  614. if errMessage != "" {
  615. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  616. return
  617. }
  618. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  619. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  620. ImageDescription: form.Description,
  621. ImageTag: form.Tag,
  622. },
  623. IsPrivate: form.IsPrivate,
  624. CloudBrainType: form.Type,
  625. Topics: validTopics,
  626. UID: ctx.User.ID,
  627. Type: models.GetRecommondType(form.IsRecommend),
  628. Place: form.Place,
  629. })
  630. if err != nil {
  631. log.Error("CommitImagefailed")
  632. if models.IsErrImageTagExist(err) {
  633. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  634. } else if models.IsErrorImageCommitting(err) {
  635. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  636. } else {
  637. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  638. }
  639. return
  640. }
  641. ctx.JSON(200, models.BaseOKMessage)
  642. }
  643. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  644. if !NamePattern.MatchString(form.Tag) {
  645. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  646. return
  647. }
  648. if utf8.RuneCountInString(form.Description) > 255 {
  649. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  650. return
  651. }
  652. validTopics, errMessage := checkTopics(form.Topics)
  653. if errMessage != "" {
  654. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  655. return
  656. }
  657. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  658. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  659. Ip: ctx.Cloudbrain.ContainerIp,
  660. TaskContainerId: ctx.Cloudbrain.ContainerID,
  661. ImageDescription: form.Description,
  662. ImageTag: form.Tag,
  663. },
  664. IsPrivate: form.IsPrivate,
  665. CloudBrainType: form.Type,
  666. Topics: validTopics,
  667. UID: ctx.User.ID,
  668. })
  669. if err != nil {
  670. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  671. if models.IsErrImageTagExist(err) {
  672. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  673. } else if models.IsErrorImageCommitting(err) {
  674. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  675. } else {
  676. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  677. }
  678. return
  679. }
  680. ctx.JSON(200, models.BaseOKMessage)
  681. }
  682. func checkTopics(Topics string) ([]string, string) {
  683. var topics = make([]string, 0)
  684. var topicsStr = strings.TrimSpace(Topics)
  685. if len(topicsStr) > 0 {
  686. topics = strings.Split(topicsStr, ",")
  687. }
  688. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  689. if len(validTopics) > 25 {
  690. return nil, "repo.topic.count_prompt"
  691. }
  692. if len(invalidTopics) > 0 {
  693. return nil, "repo.imagetopic.format_prompt"
  694. }
  695. return validTopics, ""
  696. }
  697. func CloudBrainStop(ctx *context.Context) {
  698. var ID = ctx.Params(":id")
  699. var resultCode = "0"
  700. var errorMsg = ""
  701. var status = ""
  702. task := ctx.Cloudbrain
  703. for {
  704. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  705. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  706. resultCode = "-1"
  707. errorMsg = "system error"
  708. break
  709. }
  710. err := cloudbrain.StopJob(task.JobID)
  711. if err != nil {
  712. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  713. resultCode = "-1"
  714. errorMsg = "system error"
  715. break
  716. }
  717. task.Status = string(models.JobStopped)
  718. if task.EndTime == 0 {
  719. task.EndTime = timeutil.TimeStampNow()
  720. }
  721. task.ComputeAndSetDuration()
  722. err = models.UpdateJob(task)
  723. if err != nil {
  724. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  725. resultCode = "-1"
  726. errorMsg = "system error"
  727. break
  728. }
  729. status = task.Status
  730. break
  731. }
  732. ctx.JSON(200, map[string]interface{}{
  733. "result_code": resultCode,
  734. "error_msg": errorMsg,
  735. "status": status,
  736. "id": ID,
  737. "StatusOK": 0,
  738. })
  739. }
  740. func StopJobsByUserID(userID int64) {
  741. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  742. if err != nil {
  743. log.Warn("Failed to get cloudBrain info", err)
  744. return
  745. }
  746. StopJobs(cloudBrains)
  747. }
  748. func StopJobsByRepoID(repoID int64) {
  749. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  750. if err != nil {
  751. log.Warn("Failed to get cloudBrain info", err)
  752. return
  753. }
  754. StopJobs(cloudBrains)
  755. }
  756. /**
  757. */
  758. func StopJobs(cloudBrains []*models.Cloudbrain) {
  759. for _, taskInfo := range cloudBrains {
  760. if taskInfo.Type == models.TypeCloudBrainOne {
  761. err := retry(3, time.Second*30, func() error {
  762. return cloudbrain.StopJob(taskInfo.JobID)
  763. })
  764. logErrorAndUpdateJobStatus(err, taskInfo)
  765. } else {
  766. if taskInfo.JobType == string(models.JobTypeTrain) {
  767. err := retry(3, time.Second*30, func() error {
  768. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  769. return err
  770. })
  771. logErrorAndUpdateJobStatus(err, taskInfo)
  772. } else {
  773. param := models.NotebookAction{
  774. Action: models.ActionStop,
  775. }
  776. err := retry(3, time.Second*30, func() error {
  777. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  778. return err
  779. })
  780. logErrorAndUpdateJobStatus(err, taskInfo)
  781. }
  782. }
  783. }
  784. }
  785. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  786. for i := 0; i < attempts; i++ {
  787. if i > 0 {
  788. log.Warn("retrying after error:", err)
  789. time.Sleep(sleep)
  790. }
  791. err = f()
  792. if err == nil {
  793. return nil
  794. }
  795. }
  796. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  797. }
  798. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  799. if err != nil {
  800. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  801. } else {
  802. taskInfo.Status = string(models.JobStopped)
  803. if taskInfo.EndTime == 0 {
  804. taskInfo.EndTime = timeutil.TimeStampNow()
  805. }
  806. taskInfo.ComputeAndSetDuration()
  807. err = models.UpdateJob(taskInfo)
  808. if err != nil {
  809. log.Warn("UpdateJob failed", err)
  810. }
  811. }
  812. }
  813. func CloudBrainDel(ctx *context.Context) {
  814. var listType = ctx.Query("debugListType")
  815. if err := deleteCloudbrainJob(ctx); err != nil {
  816. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  817. ctx.ServerError(err.Error(), err)
  818. return
  819. }
  820. var isAdminPage = ctx.Query("isadminpage")
  821. var isHomePage = ctx.Query("ishomepage")
  822. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  823. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  824. } else if isHomePage == "true" {
  825. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  826. } else {
  827. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  828. }
  829. }
  830. func deleteCloudbrainJob(ctx *context.Context) error {
  831. task := ctx.Cloudbrain
  832. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  833. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  834. return errors.New("the job has not been stopped")
  835. }
  836. err := models.DeleteJob(task)
  837. if err != nil {
  838. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  839. return err
  840. }
  841. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  842. return nil
  843. }
  844. func CloudBrainShowModels(ctx *context.Context) {
  845. ctx.Data["PageIsCloudBrain"] = true
  846. ID := ctx.Params(":id")
  847. parentDir := ctx.Query("parentDir")
  848. dirArray := strings.Split(parentDir, "/")
  849. task, err := models.GetCloudbrainByID(ID)
  850. if err != nil {
  851. log.Error("no such job!", ctx.Data["msgID"])
  852. ctx.ServerError("no such job:", err)
  853. return
  854. }
  855. //get dirs
  856. dirs, err := GetModelDirs(task.JobName, parentDir)
  857. if err != nil {
  858. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  859. ctx.ServerError("GetModelDirs failed:", err)
  860. return
  861. }
  862. var fileInfos []storage.FileInfo
  863. err = json.Unmarshal([]byte(dirs), &fileInfos)
  864. if err != nil {
  865. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  866. ctx.ServerError("json.Unmarshal failed:", err)
  867. return
  868. }
  869. for i, fileInfo := range fileInfos {
  870. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  871. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  872. }
  873. sort.Slice(fileInfos, func(i, j int) bool {
  874. return fileInfos[i].ModTime > fileInfos[j].ModTime
  875. })
  876. ctx.Data["Path"] = dirArray
  877. ctx.Data["Dirs"] = fileInfos
  878. ctx.Data["task"] = task
  879. ctx.Data["ID"] = ID
  880. ctx.HTML(200, tplCloudBrainShowModels)
  881. }
  882. func GetPublicImages(ctx *context.Context) {
  883. uid := getUID(ctx)
  884. opts := models.SearchImageOptions{
  885. IncludePublicOnly: true,
  886. UID: uid,
  887. Keyword: ctx.Query("q"),
  888. Topics: ctx.Query("topic"),
  889. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  890. SearchOrderBy: "type desc, num_stars desc,id desc",
  891. Status: models.IMAGE_STATUS_SUCCESS,
  892. }
  893. getImages(ctx, &opts)
  894. }
  895. func GetCustomImages(ctx *context.Context) {
  896. uid := getUID(ctx)
  897. opts := models.SearchImageOptions{
  898. UID: uid,
  899. IncludeOwnerOnly: true,
  900. Keyword: ctx.Query("q"),
  901. Topics: ctx.Query("topic"),
  902. Status: -1,
  903. SearchOrderBy: "id desc",
  904. }
  905. getImages(ctx, &opts)
  906. }
  907. func GetStarImages(ctx *context.Context) {
  908. uid := getUID(ctx)
  909. opts := models.SearchImageOptions{
  910. UID: uid,
  911. IncludeStarByMe: true,
  912. Keyword: ctx.Query("q"),
  913. Topics: ctx.Query("topic"),
  914. Status: models.IMAGE_STATUS_SUCCESS,
  915. SearchOrderBy: "id desc",
  916. }
  917. getImages(ctx, &opts)
  918. }
  919. func getUID(ctx *context.Context) int64 {
  920. var uid int64 = -1
  921. if ctx.IsSigned {
  922. uid = ctx.User.ID
  923. }
  924. return uid
  925. }
  926. func GetAllImages(ctx *context.Context) {
  927. uid := getUID(ctx)
  928. opts := models.SearchImageOptions{
  929. UID: uid,
  930. Keyword: ctx.Query("q"),
  931. Topics: ctx.Query("topic"),
  932. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  933. SearchOrderBy: "id desc",
  934. Status: -1,
  935. }
  936. if ctx.Query("private") != "" {
  937. if ctx.QueryBool("private") {
  938. opts.IncludePrivateOnly = true
  939. } else {
  940. opts.IncludePublicOnly = true
  941. }
  942. }
  943. getImages(ctx, &opts)
  944. }
  945. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  946. page := ctx.QueryInt("page")
  947. if page <= 0 {
  948. page = 1
  949. }
  950. pageSize := ctx.QueryInt("pageSize")
  951. if pageSize <= 0 {
  952. pageSize = 15
  953. }
  954. opts.ListOptions = models.ListOptions{
  955. Page: page,
  956. PageSize: pageSize,
  957. }
  958. imageList, total, err := models.SearchImage(opts)
  959. if err != nil {
  960. log.Error("Can not get images:%v", err)
  961. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  962. Count: 0,
  963. Images: []*models.Image{},
  964. })
  965. } else {
  966. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  967. Count: total,
  968. Images: imageList,
  969. })
  970. }
  971. }
  972. func GetModelDirs(jobName string, parentDir string) (string, error) {
  973. var req string
  974. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  975. if parentDir == "" {
  976. req = "baseDir=" + modelActualPath
  977. } else {
  978. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  979. }
  980. return getDirs(req)
  981. }
  982. func CloudBrainDownloadModel(ctx *context.Context) {
  983. parentDir := ctx.Query("parentDir")
  984. fileName := ctx.Query("fileName")
  985. jobName := ctx.Query("jobName")
  986. filePath := "jobs/" + jobName + "/model/" + parentDir
  987. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  988. if err != nil {
  989. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  990. ctx.ServerError("PresignedGetURL", err)
  991. return
  992. }
  993. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  994. }
  995. func GetRate(ctx *context.Context) {
  996. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  997. if isObjectDetcionAll {
  998. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  999. return
  1000. }
  1001. var ID = ctx.Params(":id")
  1002. job, err := models.GetCloudbrainByID(ID)
  1003. if err != nil {
  1004. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1005. return
  1006. }
  1007. if job.JobType == string(models.JobTypeBenchmark) {
  1008. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1009. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1010. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1011. ctx.Redirect(setting.Snn4imagenetServerHost)
  1012. } else if job.JobType == string(models.JobTypeBrainScore) {
  1013. ctx.Redirect(setting.BrainScoreServerHost)
  1014. } else {
  1015. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1016. }
  1017. }
  1018. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1019. //add "file:///" prefix to make the depth valid
  1020. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1021. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1022. return err
  1023. }
  1024. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1025. if err != nil {
  1026. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1027. return err
  1028. }
  1029. defer configFile.Close()
  1030. pos := int64(0)
  1031. reader := bufio.NewReader(configFile)
  1032. for {
  1033. line, err := reader.ReadString('\n')
  1034. if err != nil {
  1035. if err == io.EOF {
  1036. log.Error("not find the remote-url")
  1037. return nil
  1038. } else {
  1039. log.Error("read error: %v", err)
  1040. return err
  1041. }
  1042. }
  1043. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1044. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1045. if len(line) > len(originUrl) {
  1046. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1047. }
  1048. bytes := []byte(originUrl)
  1049. _, err := configFile.WriteAt(bytes, pos)
  1050. if err != nil {
  1051. log.Error("WriteAt failed:%v", err)
  1052. return err
  1053. }
  1054. break
  1055. }
  1056. pos += int64(len(line))
  1057. }
  1058. return nil
  1059. }
  1060. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  1061. err := os.MkdirAll(codePath, os.ModePerm)
  1062. if err != nil {
  1063. log.Error("mkdir codePath failed", err.Error())
  1064. return err
  1065. }
  1066. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1067. if err != nil {
  1068. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1069. return err
  1070. }
  1071. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1072. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1073. return err
  1074. }
  1075. fileName := codePath + cloudbrain.TaskInfoName
  1076. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1077. if err != nil {
  1078. log.Error("OpenFile failed", err.Error())
  1079. return err
  1080. }
  1081. defer f.Close()
  1082. data, err := json.Marshal(models.TaskInfo{
  1083. Username: repo.Owner.Name,
  1084. TaskName: taskName,
  1085. CodeName: repo.Name,
  1086. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1087. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1088. GpuType: gpuType,
  1089. })
  1090. if err != nil {
  1091. log.Error("json.Marshal failed", err.Error())
  1092. return err
  1093. }
  1094. _, err = f.Write(data)
  1095. if err != nil {
  1096. log.Error("WriteString failed", err.Error())
  1097. return err
  1098. }
  1099. return nil
  1100. }
  1101. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1102. files, err := readDir(codePath)
  1103. if err != nil {
  1104. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1105. return err
  1106. }
  1107. for _, file := range files {
  1108. if file.IsDir() {
  1109. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1110. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1111. return err
  1112. }
  1113. } else {
  1114. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1115. sourceFile := codePath + file.Name()
  1116. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1117. if err != nil {
  1118. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1119. return err
  1120. }
  1121. }
  1122. }
  1123. return nil
  1124. }
  1125. func mkModelPath(modelPath string) error {
  1126. err := os.MkdirAll(modelPath, os.ModePerm)
  1127. if err != nil {
  1128. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  1129. return err
  1130. }
  1131. fileName := modelPath + "README"
  1132. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1133. if err != nil {
  1134. log.Error("OpenFile failed", err.Error())
  1135. return err
  1136. }
  1137. defer f.Close()
  1138. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  1139. if err != nil {
  1140. log.Error("WriteString failed", err.Error())
  1141. return err
  1142. }
  1143. return nil
  1144. }
  1145. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1146. //delete local
  1147. localJobPath := setting.JobPath + jobName
  1148. err := os.RemoveAll(localJobPath)
  1149. if err != nil {
  1150. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1151. }
  1152. //delete oss
  1153. if cloudbrainType == models.TypeCloudBrainOne {
  1154. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1155. err = storage.Attachments.DeleteDir(dirPath)
  1156. if err != nil {
  1157. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1158. }
  1159. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1160. //dirPath := setting.CodePathPrefix + jobName + "/"
  1161. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1162. //if err != nil {
  1163. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1164. //}
  1165. log.Info("no need to delete")
  1166. } else {
  1167. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1168. }
  1169. return nil
  1170. }
  1171. func SyncCloudbrainStatus() {
  1172. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1173. if err != nil {
  1174. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1175. return
  1176. }
  1177. for _, task := range cloudBrains {
  1178. if task.Type == models.TypeCloudBrainOne {
  1179. result, err := cloudbrain.GetJob(task.JobID)
  1180. if err != nil {
  1181. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1182. continue
  1183. }
  1184. if result != nil {
  1185. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1186. taskRoles := jobRes.TaskRoles
  1187. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1188. task.Status = taskRes.TaskStatuses[0].State
  1189. if task.Status != string(models.JobWaiting) {
  1190. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1191. err = models.UpdateJob(task)
  1192. if err != nil {
  1193. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1194. }
  1195. var maxDuration int64
  1196. if task.JobType == string(models.JobTypeBenchmark) {
  1197. maxDuration = setting.BenchmarkMaxDuration
  1198. } else {
  1199. maxDuration = setting.MaxDuration
  1200. }
  1201. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1202. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1203. err = cloudbrain.StopJob(task.JobID)
  1204. if err != nil {
  1205. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1206. continue
  1207. }
  1208. task.Status = string(models.JobStopped)
  1209. if task.EndTime == 0 {
  1210. task.EndTime = timeutil.TimeStampNow()
  1211. }
  1212. task.ComputeAndSetDuration()
  1213. err = models.UpdateJob(task)
  1214. if err != nil {
  1215. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1216. continue
  1217. }
  1218. }
  1219. }
  1220. }
  1221. } else if task.Type == models.TypeCloudBrainTwo {
  1222. if task.JobType == string(models.JobTypeDebug) {
  1223. //result, err := modelarts.GetJob(task.JobID)
  1224. result, err := modelarts.GetNotebook2(task.JobID)
  1225. if err != nil {
  1226. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1227. continue
  1228. }
  1229. if result != nil {
  1230. task.Status = result.Status
  1231. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1232. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1233. }
  1234. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1235. task.EndTime = timeutil.TimeStampNow()
  1236. }
  1237. task.CorrectCreateUnix()
  1238. task.ComputeAndSetDuration()
  1239. err = models.UpdateJob(task)
  1240. if err != nil {
  1241. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1242. continue
  1243. }
  1244. }
  1245. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1246. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1247. if err != nil {
  1248. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1249. continue
  1250. }
  1251. if result != nil {
  1252. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1253. task.Duration = result.Duration / 1000
  1254. task.TrainJobDuration = result.TrainJobDuration
  1255. if task.StartTime == 0 && result.StartTime > 0 {
  1256. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1257. }
  1258. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1259. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1260. task.EndTime = task.StartTime.Add(task.Duration)
  1261. }
  1262. task.CorrectCreateUnix()
  1263. err = models.UpdateJob(task)
  1264. if err != nil {
  1265. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1266. continue
  1267. }
  1268. }
  1269. } else {
  1270. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1271. }
  1272. } else {
  1273. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1274. }
  1275. }
  1276. return
  1277. }
  1278. func HandleTaskWithNoDuration(ctx *context.Context) {
  1279. mode := ctx.Query("mode")
  1280. log.Info("HandleTaskWithNoDuration start")
  1281. count := 0
  1282. start := time.Now().Unix()
  1283. for {
  1284. var cloudBrains []*models.Cloudbrain
  1285. var err error
  1286. if mode == "1" {
  1287. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1288. } else {
  1289. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1290. }
  1291. if err != nil {
  1292. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1293. break
  1294. }
  1295. if len(cloudBrains) == 0 {
  1296. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1297. break
  1298. }
  1299. handleNoDurationTask(cloudBrains)
  1300. count += len(cloudBrains)
  1301. if len(cloudBrains) < 100 {
  1302. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1303. break
  1304. }
  1305. if time.Now().Unix()-start > 600 {
  1306. log.Info("HandleTaskWithNoDuration : time out")
  1307. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1308. return
  1309. }
  1310. }
  1311. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1312. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1313. }
  1314. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1315. for _, task := range cloudBrains {
  1316. time.Sleep(time.Millisecond * 100)
  1317. log.Info("Handle job ,%+v", task)
  1318. if task.Type == models.TypeCloudBrainOne {
  1319. result, err := cloudbrain.GetJob(task.JobID)
  1320. if err != nil {
  1321. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1322. updateDefaultDuration(task)
  1323. continue
  1324. }
  1325. if result != nil {
  1326. if result.Msg != "success" {
  1327. updateDefaultDuration(task)
  1328. continue
  1329. }
  1330. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1331. if err != nil || len(jobRes.TaskRoles) == 0 {
  1332. updateDefaultDuration(task)
  1333. continue
  1334. }
  1335. taskRoles := jobRes.TaskRoles
  1336. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1337. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1338. updateDefaultDuration(task)
  1339. continue
  1340. }
  1341. task.Status = taskRes.TaskStatuses[0].State
  1342. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1343. if jobRes.JobStatus.CreatedTime > 0 {
  1344. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1345. if jobRes.JobStatus.CompletedTime > 0 {
  1346. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1347. } else {
  1348. task.EndTime = task.UpdatedUnix
  1349. }
  1350. } else {
  1351. task.StartTime = 0
  1352. task.EndTime = 0
  1353. }
  1354. if task.EndTime < task.StartTime {
  1355. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1356. st := task.StartTime
  1357. task.StartTime = task.EndTime
  1358. task.EndTime = st
  1359. }
  1360. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1361. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1362. err = models.UpdateJob(task)
  1363. if err != nil {
  1364. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1365. }
  1366. }
  1367. } else if task.Type == models.TypeCloudBrainTwo {
  1368. if task.JobType == string(models.JobTypeDebug) {
  1369. //result, err := modelarts.GetJob(task.JobID)
  1370. result, err := modelarts.GetNotebook2(task.JobID)
  1371. if err != nil {
  1372. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1373. updateDefaultDuration(task)
  1374. continue
  1375. }
  1376. if result != nil {
  1377. task.Status = result.Status
  1378. startTime := result.Lease.CreateTime
  1379. duration := result.Lease.Duration / 1000
  1380. if startTime > 0 {
  1381. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1382. task.EndTime = task.StartTime.Add(duration)
  1383. }
  1384. task.CorrectCreateUnix()
  1385. task.ComputeAndSetDuration()
  1386. err = models.UpdateJob(task)
  1387. if err != nil {
  1388. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1389. continue
  1390. }
  1391. }
  1392. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1393. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1394. if err != nil {
  1395. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1396. updateDefaultDuration(task)
  1397. continue
  1398. }
  1399. if result != nil {
  1400. startTime := result.StartTime / 1000
  1401. if startTime > 0 {
  1402. task.StartTime = timeutil.TimeStamp(startTime)
  1403. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1404. }
  1405. task.ComputeAndSetDuration()
  1406. err = models.UpdateJob(task)
  1407. if err != nil {
  1408. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1409. continue
  1410. }
  1411. }
  1412. } else {
  1413. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1414. }
  1415. } else {
  1416. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1417. }
  1418. }
  1419. }
  1420. func updateDefaultDuration(task *models.Cloudbrain) {
  1421. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1422. task.StartTime = task.CreatedUnix
  1423. task.EndTime = task.UpdatedUnix
  1424. task.ComputeAndSetDuration()
  1425. err := models.UpdateJob(task)
  1426. if err != nil {
  1427. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1428. }
  1429. }
  1430. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1431. MustEnableCloudbrain(ctx)
  1432. repo := ctx.Repo.Repository
  1433. page := ctx.QueryInt("page")
  1434. if page <= 0 {
  1435. page = 1
  1436. }
  1437. var jobTypes []string
  1438. jobTypes = append(jobTypes, string(models.JobTypeBenchmark))
  1439. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1440. ListOptions: models.ListOptions{
  1441. Page: page,
  1442. PageSize: setting.UI.IssuePagingNum,
  1443. },
  1444. RepoID: repo.ID,
  1445. Type: models.TypeCloudBrainOne,
  1446. JobTypes: jobTypes,
  1447. })
  1448. if err != nil {
  1449. ctx.ServerError("Get debugjob faild:", err)
  1450. return
  1451. }
  1452. for i, task := range ciTasks {
  1453. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1454. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1455. if ciTasks[i].TrainJobDuration == "" {
  1456. if ciTasks[i].Duration == 0 {
  1457. var duration int64
  1458. if task.Status == string(models.JobRunning) {
  1459. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1460. } else {
  1461. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1462. }
  1463. ciTasks[i].Duration = duration
  1464. }
  1465. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1466. }
  1467. ciTasks[i].BenchmarkTypeName = ""
  1468. if task.BenchmarkTypeID > 0 {
  1469. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1470. if task.BenchmarkTypeID == benchmarkType.Id {
  1471. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1472. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1473. break
  1474. }
  1475. }
  1476. }
  1477. }
  1478. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1479. ctx.Data["Page"] = pager
  1480. ctx.Data["PageIsCloudBrain"] = true
  1481. ctx.Data["Tasks"] = ciTasks
  1482. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1483. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1484. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1485. }
  1486. func GetChildTypes(ctx *context.Context) {
  1487. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1488. re := make(map[string]interface{})
  1489. for {
  1490. var isExist bool
  1491. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1492. if benchmarkTypeID == benchmarkType.Id {
  1493. isExist = true
  1494. re["child_types"] = benchmarkType.Second
  1495. re["result_code"] = "0"
  1496. break
  1497. }
  1498. }
  1499. if !isExist {
  1500. re["result_code"] = "1"
  1501. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1502. re["errMsg"] = "system error"
  1503. break
  1504. }
  1505. break
  1506. }
  1507. ctx.JSON(200, re)
  1508. }
  1509. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1510. ctx.Data["description"] = ""
  1511. ctx.Data["benchmarkTypeID"] = -1
  1512. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1513. err := cloudBrainNewDataPrepare(ctx)
  1514. if err != nil {
  1515. ctx.ServerError("get new cloudbrain info failed", err)
  1516. return
  1517. }
  1518. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1519. }
  1520. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1521. var childInfo *models.BenchmarkDataset
  1522. var isExist bool
  1523. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1524. if benchmarkType.Id == benchmarkTypeID {
  1525. for _, childType := range benchmarkType.Second {
  1526. if childType.Id == benchmarkChildTypeID {
  1527. childInfo = childType
  1528. isExist = true
  1529. break
  1530. }
  1531. }
  1532. break
  1533. }
  1534. }
  1535. if !isExist {
  1536. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1537. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1538. }
  1539. return childInfo, nil
  1540. }
  1541. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1542. queue := ""
  1543. if benchmarkGpuInfos == nil {
  1544. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1545. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1546. return queue, err
  1547. }
  1548. }
  1549. var isExist bool
  1550. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1551. if gpuQueue == gpuInfo.Queue {
  1552. isExist = true
  1553. queue = gpuQueue
  1554. break
  1555. }
  1556. }
  1557. if !isExist {
  1558. log.Error("no such gpuQueue, %s", gpuQueue)
  1559. return queue, errors.New("no such gpuQueue")
  1560. }
  1561. return queue, nil
  1562. }
  1563. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1564. var id int
  1565. if benchmarkResourceSpecs == nil {
  1566. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1567. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1568. return id, err
  1569. }
  1570. }
  1571. var isExist bool
  1572. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1573. if resourceSpecID == resourceSpec.Id {
  1574. isExist = true
  1575. id = resourceSpecID
  1576. break
  1577. }
  1578. }
  1579. if !isExist {
  1580. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1581. return id, errors.New("no such resourceSpec")
  1582. }
  1583. return id, nil
  1584. }
  1585. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1586. ctx.Data["PageIsCloudBrain"] = true
  1587. displayJobName := form.DisplayJobName
  1588. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1589. image := form.Image
  1590. gpuQueue := form.GpuType
  1591. command := cloudbrain.CommandBenchmark
  1592. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1593. resourceSpecId := cloudbrain.BenchMarkResourceID
  1594. benchmarkTypeID := form.BenchmarkTypeID
  1595. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1596. ctx.Data["description"] = form.Description
  1597. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1598. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1599. repo := ctx.Repo.Repository
  1600. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1601. if err == nil {
  1602. if len(tasks) != 0 {
  1603. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1604. cloudBrainNewDataPrepare(ctx)
  1605. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1606. return
  1607. }
  1608. } else {
  1609. if !models.IsErrJobNotExist(err) {
  1610. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1611. cloudBrainNewDataPrepare(ctx)
  1612. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1613. return
  1614. }
  1615. }
  1616. if !jobNamePattern.MatchString(jobName) {
  1617. cloudBrainNewDataPrepare(ctx)
  1618. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1619. return
  1620. }
  1621. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1622. if err != nil {
  1623. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1624. cloudBrainNewDataPrepare(ctx)
  1625. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1626. return
  1627. }
  1628. _, err = getBenchmarkGpuQueue(gpuQueue)
  1629. if err != nil {
  1630. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1631. cloudBrainNewDataPrepare(ctx)
  1632. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1633. return
  1634. }
  1635. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1636. if err != nil {
  1637. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1638. cloudBrainNewDataPrepare(ctx)
  1639. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1640. return
  1641. }
  1642. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeBenchmark))
  1643. if err != nil {
  1644. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1645. cloudBrainNewDataPrepare(ctx)
  1646. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1647. return
  1648. } else {
  1649. if count >= 1 {
  1650. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1651. cloudBrainNewDataPrepare(ctx)
  1652. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainBenchmarkNew, &form)
  1653. return
  1654. }
  1655. }
  1656. os.RemoveAll(codePath)
  1657. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1658. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1659. cloudBrainNewDataPrepare(ctx)
  1660. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1661. return
  1662. }
  1663. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1664. if os.IsNotExist(err) {
  1665. // file does not exist
  1666. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1667. cloudBrainNewDataPrepare(ctx)
  1668. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1669. } else {
  1670. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1671. cloudBrainNewDataPrepare(ctx)
  1672. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1673. }
  1674. return
  1675. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1676. if os.IsNotExist(err) {
  1677. // file does not exist
  1678. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1679. cloudBrainNewDataPrepare(ctx)
  1680. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1681. } else {
  1682. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1683. cloudBrainNewDataPrepare(ctx)
  1684. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1685. }
  1686. return
  1687. }
  1688. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1689. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1690. cloudBrainNewDataPrepare(ctx)
  1691. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1692. return
  1693. }
  1694. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1695. var gpuType string
  1696. for _, gpuInfo := range gpuInfos.GpuInfo {
  1697. if gpuInfo.Queue == gpuQueue {
  1698. gpuType = gpuInfo.Value
  1699. }
  1700. }
  1701. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType); err != nil {
  1702. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1703. //cloudBrainNewDataPrepare(ctx)
  1704. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1705. //return
  1706. }
  1707. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1708. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1709. //cloudBrainNewDataPrepare(ctx)
  1710. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1711. //return
  1712. }
  1713. err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1714. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1715. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1716. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description, cloudbrain.DefaultBranchName, "", "",
  1717. benchmarkTypeID, benchmarkChildTypeID, resourceSpecId)
  1718. if err != nil {
  1719. cloudBrainNewDataPrepare(ctx)
  1720. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1721. return
  1722. }
  1723. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1724. }
  1725. func BenchmarkDel(ctx *context.Context) {
  1726. if err := deleteCloudbrainJob(ctx); err != nil {
  1727. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1728. ctx.ServerError(err.Error(), err)
  1729. return
  1730. }
  1731. var isAdminPage = ctx.Query("isadminpage")
  1732. var isHomePage = ctx.Query("ishomepage")
  1733. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1734. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1735. } else if isHomePage == "true" {
  1736. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1737. } else {
  1738. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1739. }
  1740. }
  1741. func CloudBrainTrainJobNew(ctx *context.Context) {
  1742. err := cloudBrainNewDataPrepare(ctx)
  1743. if err != nil {
  1744. ctx.ServerError("get new train-job info failed", err)
  1745. return
  1746. }
  1747. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  1748. }
  1749. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  1750. var command string
  1751. bootFile := form.BootFile
  1752. params := form.Params
  1753. if !strings.HasSuffix(bootFile, ".py") {
  1754. log.Error("bootFile(%s) format error", bootFile)
  1755. return command, errors.New("bootFile format error")
  1756. }
  1757. var parameters models.Parameters
  1758. var param string
  1759. if len(params) != 0 {
  1760. err := json.Unmarshal([]byte(params), &parameters)
  1761. if err != nil {
  1762. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1763. return command, err
  1764. }
  1765. for _, parameter := range parameters.Parameter {
  1766. param += " --" + parameter.Label + "=" + parameter.Value
  1767. }
  1768. }
  1769. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  1770. return command, nil
  1771. }
  1772. func CloudBrainTrainJobDel(ctx *context.Context) {
  1773. var listType = ctx.Query("listType")
  1774. if err := deleteCloudbrainJob(ctx); err != nil {
  1775. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1776. ctx.ServerError(err.Error(), err)
  1777. return
  1778. }
  1779. var isAdminPage = ctx.Query("isadminpage")
  1780. var isHomePage = ctx.Query("ishomepage")
  1781. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1782. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1783. } else if isHomePage == "true" {
  1784. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1785. } else {
  1786. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1787. }
  1788. }
  1789. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  1790. var lang = ctx.Locale.Language()
  1791. if benchmarkTypesMap[lang] == nil {
  1792. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  1793. //use config
  1794. val = setting.BenchmarkTypes
  1795. var tempType *models.BenchmarkTypes
  1796. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  1797. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  1798. return &models.BenchmarkTypes{}
  1799. }
  1800. benchmarkTypesMap[lang] = tempType
  1801. }
  1802. return benchmarkTypesMap[lang]
  1803. }