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