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

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