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