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