You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 60 kB

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