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

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