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