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

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
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
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
2 years ago
3 years ago
2 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
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
4 years ago
4 years ago
4 years ago
4 years ago
2 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
2 years ago
2 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
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
2 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
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
2 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
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
2 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
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
2 years ago
2 years ago
3 years ago
2 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
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
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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
2 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
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
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
2 years ago
2 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
2 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
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "code.gitea.io/gitea/modules/util"
  10. "xorm.io/builder"
  11. "xorm.io/xorm"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. )
  16. type CloudbrainStatus string
  17. type JobType string
  18. type ModelArtsJobStatus string
  19. const (
  20. TypeCloudBrainOne int = iota
  21. TypeCloudBrainTwo
  22. TypeC2Net //智算网络
  23. TypeCDCenter //成都智算中心
  24. TypeCloudBrainAll = -1
  25. )
  26. const (
  27. NPUResource = "NPU"
  28. GPUResource = "CPU/GPU"
  29. AllResource = "all"
  30. //notebook storage category
  31. EVSCategory = "EVS"
  32. EFSCategory = "EFS"
  33. ManagedOwnership = "MANAGED"
  34. DetectedOwnership = "DEDICATED"
  35. NotebookFeature = "NOTEBOOK"
  36. DefaultFeature = "DEFAULT"
  37. JobWaiting CloudbrainStatus = "WAITING"
  38. JobStopped CloudbrainStatus = "STOPPED"
  39. JobSucceeded CloudbrainStatus = "SUCCEEDED"
  40. JobFailed CloudbrainStatus = "FAILED"
  41. JobRunning CloudbrainStatus = "RUNNING"
  42. JobTypeDebug JobType = "DEBUG"
  43. JobTypeBenchmark JobType = "BENCHMARK"
  44. JobTypeSnn4imagenet JobType = "SNN4IMAGENET"
  45. JobTypeBrainScore JobType = "BRAINSCORE"
  46. JobTypeTrain JobType = "TRAIN"
  47. JobTypeInference JobType = "INFERENCE"
  48. //notebook
  49. ModelArtsCreateQueue ModelArtsJobStatus = "CREATE_QUEUING" //免费资源创建排队中
  50. ModelArtsCreating ModelArtsJobStatus = "CREATING" //创建中
  51. ModelArtsCreateFailed ModelArtsJobStatus = "CREATE_FAILED" //创建失败
  52. ModelArtsStartQueuing ModelArtsJobStatus = "START_QUEUING" //免费资源启动排队中
  53. ModelArtsReadyToStart ModelArtsJobStatus = "READY_TO_START" //免费资源等待启动
  54. ModelArtsStarting ModelArtsJobStatus = "STARTING" //启动中
  55. ModelArtsRestarting ModelArtsJobStatus = "RESTARTING" //重启中
  56. ModelArtsStartFailed ModelArtsJobStatus = "START_FAILED" //启动失败
  57. ModelArtsRunning ModelArtsJobStatus = "RUNNING" //运行中
  58. ModelArtsStopping ModelArtsJobStatus = "STOPPING" //停止中
  59. ModelArtsStopped ModelArtsJobStatus = "STOPPED" //停止
  60. ModelArtsUnavailable ModelArtsJobStatus = "UNAVAILABLE" //故障
  61. ModelArtsDeleting ModelArtsJobStatus = "DELETING" //删除中
  62. ModelArtsDeleted ModelArtsJobStatus = "DELETED" //已删除
  63. ModelArtsResizing ModelArtsJobStatus = "RESIZING" //规格变更中
  64. ModelArtsResizFailed ModelArtsJobStatus = "RESIZE_FAILED" //规格变更失败
  65. //trainjob
  66. ModelArtsTrainJobUnknown ModelArtsJobStatus = "UNKNOWN" //作业状态未知
  67. ModelArtsTrainJobInit ModelArtsJobStatus = "INIT" //作业初始化状态
  68. ModelArtsTrainJobImageCreating ModelArtsJobStatus = "IMAGE_CREATING" //作业镜像正在创建
  69. ModelArtsTrainJobImageFailed ModelArtsJobStatus = "IMAGE_FAILED" //作业镜像创建失败
  70. ModelArtsTrainJobSubmitTrying ModelArtsJobStatus = "SUBMIT_TRYING" //作业正在提交
  71. ModelArtsTrainJobSubmitFailed ModelArtsJobStatus = "SUBMIT_FAILED" //作业提交失败
  72. ModelArtsTrainJobDeleteFailed ModelArtsJobStatus = "DELETE_FAILED" //作业删除失败
  73. ModelArtsTrainJobWaiting ModelArtsJobStatus = "WAITING" //作业正在排队中
  74. ModelArtsTrainJobRunning ModelArtsJobStatus = "RUNNING" //作业正在运行中
  75. ModelArtsTrainJobKilling ModelArtsJobStatus = "KILLING" //作业正在取消
  76. ModelArtsTrainJobCompleted ModelArtsJobStatus = "COMPLETED" //作业已经完成
  77. ModelArtsTrainJobFailed ModelArtsJobStatus = "FAILED" //作业运行失败
  78. ModelArtsTrainJobKilled ModelArtsJobStatus = "KILLED" //作业取消成功
  79. ModelArtsTrainJobCanceled ModelArtsJobStatus = "CANCELED" //作业取消
  80. ModelArtsTrainJobLost ModelArtsJobStatus = "LOST" //作业丢失
  81. ModelArtsTrainJobScaling ModelArtsJobStatus = "SCALING" //作业正在扩容
  82. ModelArtsTrainJobSubmitModelFailed ModelArtsJobStatus = "SUBMIT_MODEL_FAILED" //提交模型失败
  83. ModelArtsTrainJobDeployServiceFailed ModelArtsJobStatus = "DEPLOY_SERVICE_FAILED" //部署服务失败
  84. ModelArtsTrainJobCheckInit ModelArtsJobStatus = "CHECK_INIT" //审核作业初始化
  85. ModelArtsTrainJobCheckRunning ModelArtsJobStatus = "CHECK_RUNNING" //审核作业正在运行中
  86. ModelArtsTrainJobCheckRunningCompleted ModelArtsJobStatus = "CHECK_RUNNING_COMPLETED" //审核作业已经完成
  87. ModelArtsTrainJobCheckFailed ModelArtsJobStatus = "CHECK_FAILED" //审核作业失败
  88. DURATION_STR_ZERO = "00:00:00"
  89. //grampus
  90. GrampusStatusPending = "pending"
  91. GrampusStatusRunning = "RUNNING"
  92. GrampusStatusFailed = "FAILED"
  93. GrampusStatusSucceeded = "SUCCEEDED"
  94. GrampusStatusStopped = "STOPPED"
  95. GrampusStatusUnknown = "UNKNOWN"
  96. GrampusStatusWaiting = "WAITING"
  97. )
  98. const (
  99. //cluster
  100. OpenICluster = "OpenI"
  101. C2NetCluster = "C2Net"
  102. //AI center
  103. AICenterOfCloudBrainOne = "OpenIOne"
  104. AICenterOfCloudBrainTwo = "OpenITwo"
  105. //ComputeResource
  106. GPU = "GPU"
  107. NPU = "NPU"
  108. )
  109. type Cloudbrain struct {
  110. ID int64 `xorm:"pk autoincr"`
  111. JobID string `xorm:"INDEX NOT NULL"`
  112. JobType string `xorm:"INDEX NOT NULL DEFAULT 'DEBUG'"`
  113. JobName string
  114. DisplayJobName string
  115. Status string
  116. UserID int64 `xorm:"INDEX NOT NULL"`
  117. RepoID int64 `xorm:"INDEX NOT NULL"`
  118. SubTaskName string
  119. ContainerID string
  120. ContainerIp string
  121. CreatedUnix timeutil.TimeStamp `xorm:"INDEX"`
  122. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  123. Duration int64 `xorm:"DEFAULT 0"` //运行时长 单位秒
  124. TrainJobDuration string `xorm:"DEFAULT '00:00:00'"`
  125. Image string //镜像名称
  126. GpuQueue string //GPU类型即GPU队列
  127. ResourceSpecId int //GPU规格id
  128. DeletedAt time.Time `xorm:"deleted"`
  129. CanDebug bool `xorm:"-"`
  130. CanDel bool `xorm:"-"`
  131. CanModify bool `xorm:"-"`
  132. Type int `xorm:"INDEX"`
  133. BenchmarkTypeID int
  134. BenchmarkChildTypeID int
  135. CardType string
  136. Cluster string
  137. VersionID int64 //版本id
  138. VersionName string `xorm:"INDEX"` //当前版本
  139. Uuid string //数据集id
  140. DatasetName string `xorm:"varchar(2000)"`
  141. VersionCount int //任务的当前版本数量,不包括删除的
  142. IsLatestVersion string //是否是最新版本,1是,0否
  143. CommitID string //提交的仓库代码id
  144. PreVersionName string //父版本名称
  145. ComputeResource string //计算资源,例如npu
  146. EngineID int64 //引擎id
  147. ImageID string //grampus image_id
  148. AiCenter string //grampus ai center: center_id+center_name
  149. TrainUrl string //输出模型的obs路径
  150. BranchName string //分支名称
  151. Parameters string //传给modelarts的param参数
  152. BootFile string //启动文件
  153. DataUrl string //数据集的obs路径
  154. LogUrl string //日志输出的obs路径
  155. PreVersionId int64 //父版本的版本id
  156. FlavorCode string //modelarts上的规格id
  157. Description string `xorm:"varchar(256)"` //描述
  158. WorkServerNumber int //节点数
  159. FlavorName string //规格名称
  160. EngineName string //引擎名称
  161. TotalVersionCount int //任务的所有版本数量,包括删除的
  162. LabelName string //标签名称
  163. ModelName string //模型名称
  164. ModelVersion string //模型版本
  165. CkptName string //权重文件名称
  166. ResultUrl string //推理结果的obs路径
  167. User *User `xorm:"-"`
  168. Repo *Repository `xorm:"-"`
  169. BenchmarkType string `xorm:"-"` //算法评测,模型评测
  170. BenchmarkTypeName string `xorm:"-"`
  171. BenchmarkTypeRankLink string `xorm:"-"`
  172. StartTime timeutil.TimeStamp
  173. EndTime timeutil.TimeStamp
  174. Spec *Specification `xorm:"-"`
  175. }
  176. func (task *Cloudbrain) ComputeAndSetDuration() {
  177. var d int64
  178. if task.StartTime == 0 {
  179. d = 0
  180. } else if task.EndTime == 0 {
  181. if !task.IsTerminal() {
  182. d = time.Now().Unix() - task.StartTime.AsTime().Unix()
  183. }
  184. } else {
  185. d = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  186. }
  187. if d < 0 {
  188. d = 0
  189. }
  190. task.Duration = d
  191. task.TrainJobDuration = ConvertDurationToStr(d)
  192. }
  193. func (task *Cloudbrain) CorrectCreateUnix() {
  194. if task.StartTime > 0 && task.CreatedUnix > task.StartTime {
  195. task.CreatedUnix = task.StartTime
  196. }
  197. }
  198. func (task *Cloudbrain) IsTerminal() bool {
  199. status := task.Status
  200. return status == string(ModelArtsTrainJobCompleted) || status == string(ModelArtsTrainJobFailed) ||
  201. status == string(ModelArtsTrainJobKilled) || status == string(ModelArtsStopped) ||
  202. status == string(JobStopped) || status == string(JobFailed) ||
  203. status == string(JobSucceeded) || status == GrampusStatusFailed ||
  204. status == GrampusStatusSucceeded || status == GrampusStatusStopped
  205. }
  206. func (task *Cloudbrain) IsRunning() bool {
  207. status := task.Status
  208. return status == string(ModelArtsTrainJobRunning) || status == string(ModelArtsRunning) ||
  209. status == string(JobRunning) || status == GrampusStatusRunning
  210. }
  211. func ConvertDurationToStr(duration int64) string {
  212. if duration == 0 {
  213. return DURATION_STR_ZERO
  214. }
  215. return util.AddZero(duration/3600) + ":" + util.AddZero(duration%3600/60) + ":" + util.AddZero(duration%60)
  216. }
  217. func IsTrainJobTerminal(status string) bool {
  218. return status == string(ModelArtsTrainJobCompleted) || status == string(ModelArtsTrainJobFailed) || status == string(ModelArtsTrainJobKilled) || status == GrampusStatusFailed || status == GrampusStatusStopped || status == GrampusStatusSucceeded
  219. }
  220. func IsModelArtsDebugJobTerminal(status string) bool {
  221. return status == string(ModelArtsStopped)
  222. }
  223. func IsCloudBrainOneDebugJobTerminal(status string) bool {
  224. return status == string(JobStopped) || status == string(JobFailed) || status == string(JobSucceeded)
  225. }
  226. func ParseAndSetDurationFromCloudBrainOne(result JobResultPayload, task *Cloudbrain) {
  227. isActivated := result.JobStatus.CreatedTime > 0
  228. if task.StartTime == 0 && isActivated {
  229. task.StartTime = timeutil.TimeStamp(result.JobStatus.CreatedTime / 1000)
  230. }
  231. if task.EndTime == 0 && IsCloudBrainOneDebugJobTerminal(task.Status) && isActivated {
  232. if result.JobStatus.CompletedTime > 0 {
  233. task.EndTime = timeutil.TimeStamp(result.JobStatus.CompletedTime / 1000)
  234. }
  235. }
  236. task.CorrectCreateUnix()
  237. task.ComputeAndSetDuration()
  238. }
  239. func ParseAndSetDurationFromModelArtsNotebook(result *GetNotebook2Result, job *Cloudbrain) {
  240. if job.StartTime == 0 && result.Lease.UpdateTime > 0 {
  241. job.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  242. }
  243. job.Status = result.Status
  244. if job.EndTime == 0 && IsModelArtsDebugJobTerminal(job.Status) {
  245. job.EndTime = timeutil.TimeStampNow()
  246. }
  247. job.CorrectCreateUnix()
  248. job.ComputeAndSetDuration()
  249. }
  250. type CloudbrainInfo struct {
  251. Cloudbrain `xorm:"extends"`
  252. User `xorm:"extends"`
  253. }
  254. type CloudBrainLoginResult struct {
  255. Code string
  256. Msg string
  257. Payload map[string]interface{}
  258. }
  259. type TaskRole struct {
  260. Name string `json:"name"`
  261. TaskNumber int `json:"taskNumber"`
  262. MinSucceededTaskCount int `json:"minSucceededTaskCount"`
  263. MinFailedTaskCount int `json:"minFailedTaskCount"`
  264. CPUNumber int `json:"cpuNumber"`
  265. GPUNumber int `json:"gpuNumber"`
  266. MemoryMB int `json:"memoryMB"`
  267. ShmMB int `json:"shmMB"`
  268. Command string `json:"command"`
  269. NeedIBDevice bool `json:"needIBDevice"`
  270. IsMainRole bool `json:"isMainRole"`
  271. UseNNI bool `json:"useNNI"`
  272. }
  273. type StHostPath struct {
  274. Path string `json:"path"`
  275. MountPath string `json:"mountPath"`
  276. ReadOnly bool `json:"readOnly"`
  277. }
  278. type Volume struct {
  279. HostPath StHostPath `json:"hostPath"`
  280. }
  281. type CreateJobParams struct {
  282. JobName string `json:"jobName"`
  283. RetryCount int8 `json:"retryCount"`
  284. GpuType string `json:"gpuType"`
  285. Image string `json:"image"`
  286. TaskRoles []TaskRole `json:"taskRoles"`
  287. Volumes []Volume `json:"volumes"`
  288. }
  289. type CreateJobResult struct {
  290. Code string `json:"code"`
  291. Msg string `json:"msg"`
  292. Payload map[string]interface{} `json:"payload"`
  293. }
  294. type QueueDetailResult struct {
  295. Code string `json:"code"`
  296. Msg string `json:"msg"`
  297. Payload map[string]QueueDetail `json:"payload"`
  298. }
  299. type QueueDetail struct {
  300. JobScheduleInfo JobScheduleInfo `json:"JobScheduleInfo"`
  301. }
  302. type JobScheduleInfo struct {
  303. Pending int `json:"Pending"`
  304. Running int `json:"Running"`
  305. MedianPendingJobDurationSec int `json:"MedianPendingJobDurationSec"`
  306. }
  307. type GetJobResult struct {
  308. Code string `json:"code"`
  309. Msg string `json:"msg"`
  310. Payload map[string]interface{} `json:"payload"`
  311. }
  312. type GetImagesResult struct {
  313. Code string `json:"code"`
  314. Msg string `json:"msg"`
  315. Payload GetImagesPayload `json:"payload"`
  316. }
  317. type GetImagesPayload struct {
  318. Count int `json:"count"`
  319. TotalPages int `json:"totalPages,omitempty"`
  320. ImageInfo []*ImageInfo `json:"rows"`
  321. }
  322. type CloudbrainsOptions struct {
  323. ListOptions
  324. RepoID int64 // include all repos if empty
  325. UserID int64
  326. JobID string
  327. SortType string
  328. CloudbrainIDs []int64
  329. JobStatus []string
  330. JobStatusNot bool
  331. Keyword string
  332. Type int
  333. JobTypes []string
  334. VersionName string
  335. IsLatestVersion string
  336. JobTypeNot bool
  337. NeedRepoInfo bool
  338. RepoIDList []int64
  339. BeginTime time.Time
  340. EndTime time.Time
  341. ComputeResource string
  342. BeginTimeUnix int64
  343. EndTimeUnix int64
  344. AiCenter string
  345. NeedDeleteInfo string
  346. Cluster string
  347. }
  348. type TaskPod struct {
  349. TaskRoleStatus struct {
  350. Name string `json:"name"`
  351. } `json:"taskRoleStatus"`
  352. //TaskStatuses []struct {
  353. // TaskIndex int `json:"taskIndex"`
  354. // PodUID string `json:"podUid"`
  355. // PodIP string `json:"podIp"`
  356. // PodName string `json:"podName"`
  357. // ContainerID string `json:"containerId"`
  358. // ContainerIP string `json:"containerIp"`
  359. // ContainerGpus string `json:"containerGpus"`
  360. // State string `json:"state"`
  361. // StartAt time.Time `json:"startAt"`
  362. // FinishedAt time.Time `json:"finishedAt"`
  363. // ExitCode int `json:"exitCode"`
  364. // ExitDiagnostics string `json:"exitDiagnostics"`
  365. // RetriedCount int `json:"retriedCount"`
  366. // StartTime string
  367. // FinishedTime string
  368. //} `json:"taskStatuses"`
  369. TaskStatuses []TaskStatuses `json:"taskStatuses"`
  370. }
  371. type TaskStatuses struct {
  372. TaskIndex int `json:"taskIndex"`
  373. PodUID string `json:"podUid"`
  374. PodIP string `json:"podIp"`
  375. PodName string `json:"podName"`
  376. ContainerID string `json:"containerId"`
  377. ContainerIP string `json:"containerIp"`
  378. ContainerGpus string `json:"containerGpus"`
  379. State string `json:"state"`
  380. StartAt time.Time `json:"startAt"`
  381. FinishedAt time.Time `json:"finishedAt"`
  382. ExitCode int `json:"exitCode"`
  383. ExitDiagnostics string `json:"exitDiagnostics"`
  384. RetriedCount int `json:"retriedCount"`
  385. StartTime string
  386. FinishedTime string
  387. }
  388. type TaskInfo struct {
  389. Username string `json:"username"`
  390. TaskName string `json:"task_name"`
  391. CodeName string `json:"code_name"`
  392. BenchmarkCategory []string `json:"selected_category"`
  393. CodeLink string `json:"code_link"`
  394. GpuType string `json:"gpu_type"`
  395. }
  396. func ConvertToTaskPod(input map[string]interface{}) (TaskPod, error) {
  397. data, _ := json.Marshal(input)
  398. var taskPod TaskPod
  399. err := json.Unmarshal(data, &taskPod)
  400. taskPod.TaskStatuses[0].StartTime = time.Unix(taskPod.TaskStatuses[0].StartAt.Unix()+8*3600, 0).UTC().Format("2006-01-02 15:04:05")
  401. taskPod.TaskStatuses[0].FinishedTime = time.Unix(taskPod.TaskStatuses[0].FinishedAt.Unix()+8*3600, 0).UTC().Format("2006-01-02 15:04:05")
  402. //if the task is not finished or stopped,the cloudbrain renturns 0001-01-01 08:00:00, the finishedTime shows with -
  403. if strings.HasPrefix(taskPod.TaskStatuses[0].FinishedTime, "0001") {
  404. taskPod.TaskStatuses[0].FinishedTime = "-"
  405. }
  406. return taskPod, err
  407. }
  408. type JobResultPayload struct {
  409. ID string `json:"id"`
  410. Name string `json:"name"`
  411. Platform string `json:"platform"`
  412. JobStatus struct {
  413. Username string `json:"username"`
  414. State string `json:"state"`
  415. SubState string `json:"subState"`
  416. ExecutionType string `json:"executionType"`
  417. Retries int `json:"retries"`
  418. CreatedTime int64 `json:"createdTime"`
  419. CompletedTime int64 `json:"completedTime"`
  420. AppID string `json:"appId"`
  421. AppProgress string `json:"appProgress"`
  422. AppTrackingURL string `json:"appTrackingUrl"`
  423. AppLaunchedTime int64 `json:"appLaunchedTime"`
  424. AppCompletedTime interface{} `json:"appCompletedTime"`
  425. AppExitCode int `json:"appExitCode"`
  426. AppExitDiagnostics string `json:"appExitDiagnostics"`
  427. AppExitType interface{} `json:"appExitType"`
  428. VirtualCluster string `json:"virtualCluster"`
  429. StartTime string
  430. EndTime string
  431. } `json:"jobStatus"`
  432. TaskRoles map[string]interface{} `json:"taskRoles"`
  433. Resource struct {
  434. CPU int `json:"cpu"`
  435. Memory string `json:"memory"`
  436. NvidiaComGpu int `json:"nvidia.com/gpu"`
  437. } `json:"resource"`
  438. Config struct {
  439. Image string `json:"image"`
  440. JobID string `json:"jobId"`
  441. GpuType string `json:"gpuType"`
  442. JobName string `json:"jobName"`
  443. JobType string `json:"jobType"`
  444. TaskRoles []struct {
  445. Name string `json:"name"`
  446. ShmMB int `json:"shmMB"`
  447. Command string `json:"command"`
  448. MemoryMB int `json:"memoryMB"`
  449. CPUNumber int `json:"cpuNumber"`
  450. GpuNumber int `json:"gpuNumber"`
  451. IsMainRole bool `json:"isMainRole"`
  452. TaskNumber int `json:"taskNumber"`
  453. NeedIBDevice bool `json:"needIBDevice"`
  454. MinFailedTaskCount int `json:"minFailedTaskCount"`
  455. MinSucceededTaskCount int `json:"minSucceededTaskCount"`
  456. } `json:"taskRoles"`
  457. RetryCount int `json:"retryCount"`
  458. } `json:"config"`
  459. Userinfo struct {
  460. User string `json:"user"`
  461. OrgID string `json:"org_id"`
  462. } `json:"userinfo"`
  463. }
  464. func ConvertToJobResultPayload(input map[string]interface{}) (JobResultPayload, error) {
  465. data, _ := json.Marshal(input)
  466. var jobResultPayload JobResultPayload
  467. err := json.Unmarshal(data, &jobResultPayload)
  468. jobResultPayload.JobStatus.StartTime = time.Unix(jobResultPayload.JobStatus.CreatedTime/1000, 0).Format("2006-01-02 15:04:05")
  469. jobResultPayload.JobStatus.EndTime = time.Unix(jobResultPayload.JobStatus.CompletedTime/1000, 0).Format("2006-01-02 15:04:05")
  470. if jobResultPayload.JobStatus.State == string(JobWaiting) {
  471. jobResultPayload.JobStatus.StartTime = "-"
  472. jobResultPayload.JobStatus.EndTime = "-"
  473. }
  474. return jobResultPayload, err
  475. }
  476. type ImagesResultPayload struct {
  477. Images []struct {
  478. ID int `json:"id"`
  479. Name string `json:"name"`
  480. Place string `json:"place"`
  481. Description string `json:"description"`
  482. Provider string `json:"provider"`
  483. Createtime string `json:"createtime"`
  484. Remark string `json:"remark"`
  485. } `json:"taskStatuses"`
  486. }
  487. type ImageInfo struct {
  488. ID int `json:"id"`
  489. Name string `json:"name"`
  490. Place string `json:"place"`
  491. Description string `json:"description"`
  492. Provider string `json:"provider"`
  493. Createtime string `json:"createtime"`
  494. Remark string `json:"remark"`
  495. IsPublic int `json:"isPublic"`
  496. PlaceView string
  497. }
  498. type Categories struct {
  499. Category []*Category `json:"category"`
  500. }
  501. type Category struct {
  502. Id int `json:"id"`
  503. Value string `json:"value"`
  504. }
  505. type BenchmarkTypes struct {
  506. BenchmarkType []*BenchmarkType `json:"type"`
  507. }
  508. type BenchmarkType struct {
  509. Id int `json:"id"`
  510. RankLink string `json:"rank_link"`
  511. First string `json:"first"` //一级算法类型名称
  512. Second []*BenchmarkDataset `json:"second"`
  513. }
  514. type BenchmarkDataset struct {
  515. Id int `json:"id"`
  516. Value string `json:"value"` //二级算法类型名称
  517. Attachment string `json:"attachment"` //数据集的uuid
  518. Owner string `json:"owner"` //评估脚本所在仓库的拥有者
  519. RepoName string `json:"repo_name"` //评估脚本所在仓库的名称
  520. }
  521. type GpuInfos struct {
  522. GpuInfo []*GpuInfo `json:"gpu_type"`
  523. }
  524. type GpuInfo struct {
  525. Id int `json:"id"`
  526. Value string `json:"value"`
  527. Queue string `json:"queue"`
  528. }
  529. type ResourceSpecs struct {
  530. ResourceSpec []*ResourceSpec `json:"resorce_specs"`
  531. }
  532. type ResourceSpec struct {
  533. Id int `json:"id"`
  534. CpuNum int `json:"cpu"`
  535. GpuNum int `json:"gpu"`
  536. MemMiB int `json:"memMiB"`
  537. ShareMemMiB int `json:"shareMemMiB"`
  538. }
  539. type SpecialPools struct {
  540. Pools []*SpecialPool `json:"pools"`
  541. }
  542. type SpecialPool struct {
  543. Org string `json:"org"`
  544. Type string `json:"type"`
  545. IsExclusive bool `json:"isExclusive"`
  546. Pool []*GpuInfo `json:"pool"`
  547. JobType []string `json:"jobType"`
  548. ResourceSpec []*ResourceSpec `json:"resourceSpecs"`
  549. Flavor []*setting.FlavorInfo `json:"flavor"`
  550. }
  551. type PoolInfos struct {
  552. PoolInfo []*PoolInfo `json:"pool_info"`
  553. }
  554. type PoolInfo struct {
  555. PoolId string `json:"pool_id"`
  556. PoolName string `json:"pool_name"`
  557. PoolType string `json:"pool_type"`
  558. }
  559. type CommitImageCloudBrainParams struct {
  560. Ip string `json:"ip"`
  561. TaskContainerId string `json:"taskContainerId"`
  562. ImageTag string `json:"imageTag"`
  563. ImageDescription string `json:"imageDescription"`
  564. }
  565. type CommitImageParams struct {
  566. CommitImageCloudBrainParams
  567. IsPrivate bool
  568. Topics []string
  569. CloudBrainType int
  570. UID int64
  571. Place string
  572. Type int
  573. }
  574. type CommitImageResult struct {
  575. Code string `json:"code"`
  576. Msg string `json:"msg"`
  577. Payload map[string]interface{} `json:"payload"`
  578. }
  579. type GetJobLogParams struct {
  580. Size string `json:"size"`
  581. Sort string `json:"sort"`
  582. QueryInfo QueryInfo `json:"query"`
  583. }
  584. type QueryInfo struct {
  585. MatchInfo MatchInfo `json:"match"`
  586. }
  587. type MatchInfo struct {
  588. PodName string `json:"kubernetes.pod.name"`
  589. }
  590. type GetJobLogResult struct {
  591. ScrollID string `json:"_scroll_id"`
  592. Took int `json:"took"`
  593. TimedOut bool `json:"timed_out"`
  594. Shards struct {
  595. Total int `json:"total"`
  596. Successful int `json:"successful"`
  597. Skipped int `json:"skipped"`
  598. Failed int `json:"failed"`
  599. } `json:"_shards"`
  600. Hits struct {
  601. Hits []Hits `json:"hits"`
  602. } `json:"hits"`
  603. }
  604. type Hits struct {
  605. Index string `json:"_index"`
  606. Type string `json:"_type"`
  607. ID string `json:"_id"`
  608. Source struct {
  609. Message string `json:"message"`
  610. } `json:"_source"`
  611. Sort []int `json:"sort"`
  612. }
  613. type GetAllJobLogParams struct {
  614. Scroll string `json:"scroll"`
  615. ScrollID string `json:"scroll_id"`
  616. }
  617. type DeleteJobLogTokenParams struct {
  618. ScrollID string `json:"scroll_id"`
  619. }
  620. type DeleteJobLogTokenResult struct {
  621. Succeeded bool `json:"succeeded"`
  622. NumFreed int `json:"num_freed"`
  623. }
  624. type CloudBrainResult struct {
  625. Code string `json:"code"`
  626. Msg string `json:"msg"`
  627. }
  628. type CreateNotebook2Params struct {
  629. JobName string `json:"name"`
  630. Description string `json:"description"`
  631. Duration int64 `json:"duration"` //ms
  632. Feature string `json:"feature"`
  633. PoolID string `json:"pool_id"`
  634. Flavor string `json:"flavor"`
  635. ImageID string `json:"image_id"`
  636. WorkspaceID string `json:"workspace_id"`
  637. Volume VolumeReq `json:"volume"`
  638. }
  639. type CreateNotebookWithoutPoolParams struct {
  640. JobName string `json:"name"`
  641. Description string `json:"description"`
  642. Duration int64 `json:"duration"` //ms
  643. Feature string `json:"feature"`
  644. Flavor string `json:"flavor"`
  645. ImageID string `json:"image_id"`
  646. WorkspaceID string `json:"workspace_id"`
  647. Volume VolumeReq `json:"volume"`
  648. }
  649. type VolumeReq struct {
  650. Capacity int `json:"capacity"`
  651. Category string `json:"category"`
  652. Ownership string `json:"ownership"`
  653. Uri string `json:"uri"`
  654. }
  655. type CreateNotebookParams struct {
  656. JobName string `json:"name"`
  657. Description string `json:"description"`
  658. ProfileID string `json:"profile_id"`
  659. Flavor string `json:"flavor"`
  660. Spec Spec `json:"spec"`
  661. Workspace Workspace `json:"workspace"`
  662. Pool Pool `json:"pool"`
  663. }
  664. type Pool struct {
  665. ID string `json:"id"`
  666. Name string `json:"name"`
  667. Type string `json:"type"`
  668. }
  669. type Workspace struct {
  670. ID string `json:"id"`
  671. }
  672. type Spec struct {
  673. Storage Storage `json:"storage"`
  674. AutoStop AutoStop `json:"auto_stop"`
  675. }
  676. type AutoStop struct {
  677. Enable bool `json:"enable"`
  678. Duration int `json:"duration"`
  679. }
  680. type Storage struct {
  681. Type string `json:"type"`
  682. Location Location `json:"location"`
  683. }
  684. type Location struct {
  685. Path string `json:"path"`
  686. }
  687. type NotebookResult struct {
  688. ErrorCode string `json:"error_code"`
  689. ErrorMsg string `json:"error_msg"`
  690. }
  691. type CreateNotebookResult struct {
  692. ErrorCode string `json:"error_code"`
  693. ErrorMsg string `json:"error_msg"`
  694. ID string `json:"id"`
  695. Name string `json:"name"`
  696. Description string `json:"description"`
  697. Status string `json:"status"`
  698. CreationTimestamp string `json:"creation_timestamp"`
  699. LatestUpdateTimestamp string `json:"latest_update_timestamp"`
  700. Profile struct {
  701. ID string `json:"id"`
  702. Name string `json:"name"`
  703. Description string `json:"description"`
  704. DeType string `json:"de_type"`
  705. FlavorType string `json:"flavor_type"`
  706. } `json:"profile"`
  707. Flavor string `json:"flavor"`
  708. FlavorDetails struct {
  709. Name string `json:"name"`
  710. Status string `json:"status"`
  711. QueuingNum int `json:"queuing_num"`
  712. QueueLeftTime int `json:"queue_left_time"` //s
  713. Duration int `json:"duration"` //auto_stop_time s
  714. } `json:"flavor_details"`
  715. }
  716. type GetNotebookResult struct {
  717. ErrorCode string `json:"error_code"`
  718. ErrorMsg string `json:"error_msg"`
  719. ID string `json:"id"`
  720. Name string `json:"name"`
  721. Description string `json:"description"`
  722. Status string `json:"status"`
  723. CreationTimestamp string `json:"creation_timestamp"`
  724. CreateTime string
  725. LatestUpdateTimestamp string `json:"latest_update_timestamp"`
  726. LatestUpdateTime string
  727. Profile struct {
  728. ID string `json:"id"`
  729. Name string `json:"name"`
  730. Description string `json:"description"`
  731. DeType string `json:"de_type"`
  732. FlavorType string `json:"flavor_type"`
  733. } `json:"profile"`
  734. Flavor string `json:"flavor"`
  735. FlavorDetails struct {
  736. Name string `json:"name"`
  737. Status string `json:"status"`
  738. QueuingNum int `json:"queuing_num"`
  739. QueueLeftTime int `json:"queue_left_time"` //s
  740. Duration int `json:"duration"` //auto_stop_time s
  741. } `json:"flavor_details"`
  742. QueuingInfo struct {
  743. ID string `json:"id"`
  744. Name string `json:"name"`
  745. Flavor string `json:"flavor"`
  746. DeType string `json:"de_type"`
  747. Status string `json:"status"`
  748. BeginTimestamp int `json:"begin_timestamp"` //time of instance begin in queue
  749. BeginTime string
  750. RemainTime int `json:"remain_time"` //remain time of instance
  751. EndTimestamp int `json:"end_timestamp"` //
  752. EndTime string
  753. Rank int `json:"rank"` //rank of instance in queue
  754. } `json:"queuing_info"`
  755. Spec struct {
  756. Annotations struct {
  757. TargetDomain string `json:"target_domain"`
  758. Url string `json:"url"`
  759. } `json:"annotations"`
  760. } `json:"spec"`
  761. }
  762. type GetNotebook2Result struct {
  763. ErrorCode string `json:"error_code"`
  764. ErrorMsg string `json:"error_msg"`
  765. FailReason string `json:"fail_reason"`
  766. ID string `json:"id"`
  767. Name string `json:"name"`
  768. Description string `json:"description"`
  769. Status string `json:"status"`
  770. Url string `json:"url"` //实例访问的URL
  771. Token string `json:"token"` //notebook鉴权使用的token信息
  772. Flavor string `json:"flavor"`
  773. CreateTime string
  774. LatestUpdateTime string
  775. CreateAt int64 `json:"create_at"` //实例创建的时间,UTC毫秒
  776. UpdateAt int64 `json:"update_at"` //实例最后更新(不包括保活心跳)的时间,UTC毫秒
  777. Image struct {
  778. Name string `json:"name"`
  779. Status string `json:"status"`
  780. QueuingNum int `json:"queuing_num"`
  781. QueueLeftTime int `json:"queue_left_time"` //s
  782. Duration int `json:"duration"` //auto_stop_time s
  783. } `json:"image"`
  784. Lease struct {
  785. CreateTime int64 `json:"create_at"` //实例创建的时间,UTC毫秒
  786. Duration int64 `json:"duration"` //实例运行时长,以创建时间为起点计算,即“创建时间+duration > 当前时刻”时,系统会自动停止实例
  787. UpdateTime int64 `json:"update_at"` //实例最后更新(不包括保活心跳)的时间,UTC毫秒
  788. } `json:"lease"` //实例自动停止的倒计时信息
  789. VolumeRes struct {
  790. Capacity int `json:"capacity"`
  791. Category string `json:"category"`
  792. MountPath string `json:"mount_path"`
  793. Ownership string `json:"ownership"`
  794. Status string `json:"status"`
  795. } `json:"volume"`
  796. }
  797. type GetTokenParams struct {
  798. Auth Auth `json:"auth"`
  799. }
  800. type Auth struct {
  801. Identity Identity `json:"identity"`
  802. Scope Scope `json:"scope"`
  803. }
  804. type Scope struct {
  805. Project Project `json:"project"`
  806. }
  807. type Project struct {
  808. Name string `json:"name"`
  809. }
  810. type Identity struct {
  811. Methods []string `json:"methods"`
  812. Password Password `json:"password"`
  813. }
  814. type Password struct {
  815. User NotebookUser `json:"user"`
  816. }
  817. type NotebookUser struct {
  818. Name string `json:"name"`
  819. Password string `json:"password"`
  820. Domain Domain `json:"domain"`
  821. }
  822. type Domain struct {
  823. Name string `json:"name"`
  824. }
  825. const (
  826. ActionStart = "start"
  827. ActionStop = "stop"
  828. ActionRestart = "restart"
  829. ActionQueue = "queue"
  830. ActionDequeue = "dequeue"
  831. )
  832. type NotebookAction struct {
  833. Action string `json:"action"`
  834. }
  835. type NotebookActionResult struct {
  836. ErrorCode string `json:"error_code"`
  837. ErrorMsg string `json:"error_msg"`
  838. CurrentStatus string `json:"current_status"`
  839. PreviousState string `json:"previous_state"`
  840. Status string `json:"status"`
  841. }
  842. type NotebookGetJobTokenResult struct {
  843. ErrorCode string `json:"error_code"`
  844. ErrorMsg string `json:"error_msg"`
  845. Token string `json:"token"`
  846. }
  847. type NotebookDelResult struct {
  848. NotebookResult
  849. InstanceID string `json:"instance_id"`
  850. }
  851. type CreateUserImageTrainJobParams struct {
  852. JobName string `json:"job_name"`
  853. Description string `json:"job_desc"`
  854. Config UserImageConfig `json:"config"`
  855. WorkspaceID string `json:"workspace_id"`
  856. }
  857. type UserImageConfig struct {
  858. WorkServerNum int `json:"worker_server_num"`
  859. AppUrl string `json:"app_url"` //训练作业的代码目录
  860. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  861. Parameter []Parameter `json:"parameter"`
  862. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  863. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  864. LogUrl string `json:"log_url"`
  865. UserImageUrl string `json:"user_image_url"`
  866. UserCommand string `json:"user_command"`
  867. CreateVersion bool `json:"create_version"`
  868. Flavor Flavor `json:"flavor"`
  869. PoolID string `json:"pool_id"`
  870. }
  871. type CreateTrainJobParams struct {
  872. JobName string `json:"job_name"`
  873. Description string `json:"job_desc"`
  874. Config Config `json:"config"`
  875. WorkspaceID string `json:"workspace_id"`
  876. }
  877. type Config struct {
  878. WorkServerNum int `json:"worker_server_num"`
  879. AppUrl string `json:"app_url"` //训练作业的代码目录
  880. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  881. Parameter []Parameter `json:"parameter"`
  882. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  883. EngineID int64 `json:"engine_id"`
  884. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  885. LogUrl string `json:"log_url"`
  886. //UserImageUrl string `json:"user_image_url"`
  887. //UserCommand string `json:"user_command"`
  888. CreateVersion bool `json:"create_version"`
  889. Flavor Flavor `json:"flavor"`
  890. PoolID string `json:"pool_id"`
  891. }
  892. type CreateInferenceJobParams struct {
  893. JobName string `json:"job_name"`
  894. Description string `json:"job_desc"`
  895. InfConfig InfConfig `json:"config"`
  896. WorkspaceID string `json:"workspace_id"`
  897. }
  898. type InfConfig struct {
  899. WorkServerNum int `json:"worker_server_num"`
  900. AppUrl string `json:"app_url"` //训练作业的代码目录
  901. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  902. Parameter []Parameter `json:"parameter"`
  903. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  904. EngineID int64 `json:"engine_id"`
  905. LogUrl string `json:"log_url"`
  906. CreateVersion bool `json:"create_version"`
  907. Flavor Flavor `json:"flavor"`
  908. PoolID string `json:"pool_id"`
  909. }
  910. type CreateTrainJobVersionParams struct {
  911. Description string `json:"job_desc"`
  912. Config TrainJobVersionConfig `json:"config"`
  913. }
  914. type CreateTrainJobVersionUserImageParams struct {
  915. Description string `json:"job_desc"`
  916. Config TrainJobVersionUserImageConfig `json:"config"`
  917. }
  918. type TrainJobVersionConfig struct {
  919. WorkServerNum int `json:"worker_server_num"`
  920. AppUrl string `json:"app_url"` //训练作业的代码目录
  921. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  922. Parameter []Parameter `json:"parameter"`
  923. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  924. EngineID int64 `json:"engine_id"`
  925. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  926. LogUrl string `json:"log_url"`
  927. Flavor Flavor `json:"flavor"`
  928. PoolID string `json:"pool_id"`
  929. PreVersionId int64 `json:"pre_version_id"`
  930. }
  931. type TrainJobVersionUserImageConfig struct {
  932. WorkServerNum int `json:"worker_server_num"`
  933. AppUrl string `json:"app_url"` //训练作业的代码目录
  934. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  935. Parameter []Parameter `json:"parameter"`
  936. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  937. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  938. LogUrl string `json:"log_url"`
  939. Flavor Flavor `json:"flavor"`
  940. PoolID string `json:"pool_id"`
  941. PreVersionId int64 `json:"pre_version_id"`
  942. UserImageUrl string `json:"user_image_url"`
  943. UserCommand string `json:"user_command"`
  944. }
  945. type CreateConfigParams struct {
  946. ConfigName string `json:"config_name"`
  947. Description string `json:"config_desc"`
  948. WorkServerNum int `json:"worker_server_num"`
  949. AppUrl string `json:"app_url"` //训练作业的代码目录
  950. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  951. Parameter []Parameter `json:"parameter"`
  952. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  953. EngineID int64 `json:"engine_id"`
  954. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  955. LogUrl string `json:"log_url"`
  956. Flavor Flavor `json:"flavor"`
  957. PoolID string `json:"pool_id"`
  958. }
  959. type Parameter struct {
  960. Label string `json:"label"`
  961. Value string `json:"value"`
  962. }
  963. type Parameters struct {
  964. Parameter []Parameter `json:"parameter"`
  965. }
  966. type Datasurl struct {
  967. DatasetUrl string `json:"dataset_url"`
  968. DatasetName string `json:"dataset_name"`
  969. }
  970. type DatasetDownload struct {
  971. DatasetName string `json:"dataset_name"`
  972. DatasetDownloadLink string `json:"dataset_download_link"`
  973. RepositoryLink string `json:"repository_link"`
  974. IsDelete bool `json:"is_delete"`
  975. }
  976. type DataSource struct {
  977. DatasetID string `json:"dataset_id"`
  978. DatasetVersion string `json:"dataset_version"`
  979. Type string `json:"type"`
  980. DataUrl string `json:"data_url"`
  981. }
  982. type Volumes struct {
  983. Nfs Nfs `json:"nfs"`
  984. HostPath HostPath `json:"host_path"`
  985. }
  986. type Nfs struct {
  987. ID string `json:"id"`
  988. SourcePath string `json:"src_path"`
  989. DestPath string `json:"dest_path"`
  990. ReadOnly bool `json:"read_only"`
  991. }
  992. type HostPath struct {
  993. SourcePath string `json:"src_path"`
  994. DestPath string `json:"dest_path"`
  995. ReadOnly bool `json:"read_only"`
  996. }
  997. type Flavor struct {
  998. Code string `json:"code"`
  999. }
  1000. type CreateTrainJobResult struct {
  1001. ErrorCode string `json:"error_code"`
  1002. ErrorMsg string `json:"error_msg"`
  1003. IsSuccess bool `json:"is_success"`
  1004. JobName string `json:"job_name"`
  1005. JobID int64 `json:"job_id"`
  1006. Status int `json:"status"`
  1007. CreateTime int64 `json:"create_time"`
  1008. VersionID int64 `json:"version_id"`
  1009. ResourceID string `json:"resource_id"`
  1010. VersionName string `json:"version_name"`
  1011. }
  1012. type CreateTrainJobConfigResult struct {
  1013. ErrorCode string `json:"error_code"`
  1014. ErrorMsg string `json:"error_msg"`
  1015. IsSuccess bool `json:"is_success"`
  1016. }
  1017. type GetResourceSpecsResult struct {
  1018. ErrorCode string `json:"error_code"`
  1019. ErrorMsg string `json:"error_msg"`
  1020. IsSuccess bool `json:"is_success"`
  1021. SpecTotalCount int `json:"spec_total_count"`
  1022. Specs []Specs `json:"specs"`
  1023. }
  1024. type Specs struct {
  1025. Core string `json:"core"`
  1026. Cpu string `json:"cpu"`
  1027. IsNoResource bool `json:"no_resource"`
  1028. GpuType string `json:"gpu_type"`
  1029. SpecID int64 `json:"spec_id"`
  1030. GpuNum int `json:"gpu_num"`
  1031. SpecCode string `json:"spec_code"`
  1032. Storage string `json:"storage"`
  1033. MaxNum int `json:"max_num"`
  1034. UnitNum int `json:"unit_num"`
  1035. InterfaceType int `json:"interface_type"`
  1036. }
  1037. type GetConfigListResult struct {
  1038. ErrorCode string `json:"error_code"`
  1039. ErrorMsg string `json:"error_msg"`
  1040. IsSuccess bool `json:"is_success"`
  1041. ConfigTotalCount int `json:"config_total_count"`
  1042. ParaConfigs []ParaConfig `json:"configs"`
  1043. }
  1044. type ParaConfig struct {
  1045. ConfigName string `json:"config_name"`
  1046. ConfigDesc string `json:"config_desc"`
  1047. CreateTime int64 `json:"create_time"`
  1048. EngineType int `json:"engine_type"`
  1049. EngineName string `json:"engine_name"`
  1050. EngineId int64 `json:"engine_id"`
  1051. EngineVersion string `json:"engine_version"`
  1052. UserImageUrl string `json:"user_image_url"`
  1053. UserCommand string `json:"user_command"`
  1054. Result GetConfigResult
  1055. }
  1056. type GetConfigResult struct {
  1057. ErrorCode string `json:"error_code"`
  1058. ErrorMsg string `json:"error_msg"`
  1059. IsSuccess bool `json:"is_success"`
  1060. ConfigName string `json:"config_name"`
  1061. Description string `json:"config_desc"`
  1062. WorkServerNum int `json:"worker_server_num"`
  1063. AppUrl string `json:"app_url"` //训练作业的代码目录
  1064. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  1065. Parameter []Parameter `json:"parameter"`
  1066. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  1067. EngineID int64 `json:"engine_id"`
  1068. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  1069. LogUrl string `json:"log_url"`
  1070. Flavor Flavor `json:"flavor"`
  1071. PoolID string `json:"pool_id"`
  1072. }
  1073. type ErrorResult struct {
  1074. ErrorCode string `json:"error_code"`
  1075. ErrorMsg string `json:"error_message"`
  1076. IsSuccess bool `json:"is_success"`
  1077. }
  1078. type GetTrainJobResult struct {
  1079. IsSuccess bool `json:"is_success"`
  1080. JobName string `json:"job_name"`
  1081. JobID int64 `json:"job_id"`
  1082. Description string `json:"job_desc"`
  1083. IntStatus int `json:"status"`
  1084. Status string
  1085. LongCreateTime int64 `json:"create_time"`
  1086. CreateTime string
  1087. Duration int64 `json:"duration"` //训练作业的运行时间,单位为毫秒
  1088. TrainJobDuration string //训练作业的运行时间,格式为hh:mm:ss
  1089. VersionID int64 `json:"version_id"`
  1090. ResourceID string `json:"resource_id"`
  1091. VersionName string `json:"version_name"`
  1092. PreVersionID int64 `json:"pre_version_id"`
  1093. WorkServerNum int `json:"worker_server_num"`
  1094. AppUrl string `json:"app_url"` //训练作业的代码目录
  1095. BootFileUrl string `json:"boot_file_url"` //训练作业的代码启动文件,需要在代码目录下
  1096. Parameter []Parameter `json:"parameter"`
  1097. DataUrl string `json:"data_url"` //训练作业需要的数据集OBS路径URL
  1098. EngineID int64 `json:"engine_id"`
  1099. EngineName string `json:"engine_name"`
  1100. EngineVersion string `json:"engine_version"`
  1101. TrainUrl string `json:"train_url"` //训练作业的输出文件OBS路径URL
  1102. LogUrl string `json:"log_url"`
  1103. Flavor Flavor `json:"flavor"`
  1104. PoolID string `json:"pool_id"`
  1105. PoolName string `json:"pool_name"`
  1106. NasMountPath string `json:"nas_mount_path"`
  1107. NasShareAddr string `json:"nas_share_addr"`
  1108. DatasetName string
  1109. ModelMetricList string `json:"model_metric_list"` //列表里包含f1_score,recall,precision,accuracy,若有的话
  1110. StartTime int64 `json:"start_time"` //训练作业开始时间。
  1111. }
  1112. type GetTrainJobLogResult struct {
  1113. ErrorCode string `json:"error_code"`
  1114. ErrorMsg string `json:"error_msg"`
  1115. IsSuccess bool `json:"is_success"`
  1116. Content string `json:"content"`
  1117. Lines int `json:"lines"`
  1118. StartLine string `json:"start_line"`
  1119. EndLine string `json:"end_line"`
  1120. }
  1121. type GetTrainJobLogFileNamesResult struct {
  1122. ErrorCode string `json:"error_code"`
  1123. ErrorMsg string `json:"error_msg"`
  1124. IsSuccess bool `json:"is_success"`
  1125. LogFileList []string `json:"log_file_list"`
  1126. }
  1127. type TrainJobResult struct {
  1128. ErrorCode string `json:"error_code"`
  1129. ErrorMsg string `json:"error_msg"`
  1130. IsSuccess bool `json:"is_success"`
  1131. }
  1132. type LogFile struct {
  1133. Name string
  1134. }
  1135. type JobList struct {
  1136. JobName string `json:"job_name"`
  1137. JobID int64 `json:"job_id"`
  1138. VersionID int64 `json:"version_id"`
  1139. VersionCount int64 `json:"version_count"`
  1140. Description string `json:"job_desc"`
  1141. IntStatus int `json:"status"`
  1142. }
  1143. type GetTrainJobListResult struct {
  1144. ErrorResult
  1145. JobTotalCount int `json:"job_total_count"` //查询到的用户创建作业总数
  1146. JobCountLimit int `json:"job_count_limit"` //用户还可以创建训练作业的数量
  1147. Quotas int `json:"quotas"` //训练作业的运行数量上限
  1148. JobList []JobList `json:"jobs"`
  1149. }
  1150. type JobVersionList struct {
  1151. VersionName string `json:"version_name"`
  1152. VersionID int64 `json:"version_id"`
  1153. IntStatus int `json:"status"`
  1154. }
  1155. type GetTrainJobVersionListResult struct {
  1156. ErrorResult
  1157. JobID int64 `json:"job_id"`
  1158. JobName string `json:"job_name"`
  1159. JobDesc string `json:"job_desc"`
  1160. VersionCount int64 `json:"version_count"`
  1161. JobVersionList []JobVersionList `json:"versions"`
  1162. }
  1163. type NotebookList struct {
  1164. JobName string `json:"name"`
  1165. JobID string `json:"id"`
  1166. Status string `json:"status"`
  1167. }
  1168. type GetNotebookListResult struct {
  1169. TotalCount int64 `json:"total"` //总的记录数量
  1170. CurrentPage int `json:"current"` //当前页数
  1171. TotalPages int `json:"pages"` //总的页数
  1172. Size int `json:"size"` //每一页的数量
  1173. NotebookList []NotebookList `json:"data"`
  1174. }
  1175. //Grampus
  1176. type GrampusResult struct {
  1177. ErrorCode int `json:"errorCode"`
  1178. ErrorMsg string `json:"errorMsg"`
  1179. }
  1180. type GrampusJobInfo struct {
  1181. StartedAt int64 `json:"startedAt"`
  1182. RunSec int64 `json:"runSec"`
  1183. CompletedAt int64 `json:"completedAt"`
  1184. CreatedAt int64 `json:"createdAt"`
  1185. UpdatedAt int64 `json:"updatedAt"`
  1186. Desc string `json:"desc"`
  1187. JobID string `json:"id"`
  1188. Name string `json:"name"`
  1189. Status string `json:"status"`
  1190. UserID string `json:"userId"`
  1191. Tasks []GrampusTasks `json:"tasks"`
  1192. }
  1193. type Center struct {
  1194. ID string `json:"id"`
  1195. Name string `json:"name"`
  1196. }
  1197. type GrampusSpec struct {
  1198. CreatedAt int64 `json:"createdAt"`
  1199. UpdatedAt int64 `json:"updatedAt"`
  1200. ID string `json:"id"`
  1201. Name string `json:"name"`
  1202. ProcessorType string `json:"processorType"`
  1203. Centers []Center `json:"centers"`
  1204. SpecInfo SpecInfo `json:"specInfo"`
  1205. }
  1206. type GrampusAiCenter struct {
  1207. AccDevices []GrampusAccDevice `json:"accDevices"`
  1208. Id string `json:"id"`
  1209. Name string `json:"name"`
  1210. Resource []GrampusCenterResource `json:"resource"`
  1211. }
  1212. type GrampusAccDevice struct {
  1213. Kind string `json:"kind"` //加速卡类别, npu.huawei.com/NPU,nvidia.com/gpu,cambricon.com/mlu
  1214. Model string `json:"model"` //加速卡型号
  1215. }
  1216. type GrampusCenterResource struct {
  1217. Allocated string `json:"allocated"`
  1218. Capacity string `json:"capacity"`
  1219. Name string `json:"name"`
  1220. }
  1221. type SpecInfo struct {
  1222. AccDeviceKind string `json:"accDeviceKind"`
  1223. AccDeviceMemory string `json:"accDeviceMemory"`
  1224. AccDeviceModel string `json:"accDeviceModel"`
  1225. AccDeviceNum int `json:"accDeviceNum"`
  1226. CpuCoreNum int `json:"cpuCoreNum"`
  1227. MemorySize string `json:"memorySize"`
  1228. }
  1229. type GetGrampusResourceSpecsResult struct {
  1230. GrampusResult
  1231. Infos []GrampusSpec `json:"resourceSpecs"`
  1232. }
  1233. type GetGrampusAiCentersResult struct {
  1234. GrampusResult
  1235. Infos []GrampusAiCenter `json:"aiCenterInfos"`
  1236. TotalSize int `json:"totalSize"`
  1237. }
  1238. type GrampusImage struct {
  1239. CreatedAt int64 `json:"createdAt"`
  1240. UpdatedAt int64 `json:"updatedAt"`
  1241. ID string `json:"id"`
  1242. Name string `json:"name"`
  1243. ProcessorType string `json:"processorType"`
  1244. }
  1245. type GetGrampusImagesResult struct {
  1246. GrampusResult
  1247. TotalSize int `json:"totalSize"`
  1248. Infos []GrampusImage `json:"images"`
  1249. }
  1250. type CreateGrampusJobResponse struct {
  1251. GrampusResult
  1252. JobInfo GrampusJobInfo `json:"otJob"`
  1253. }
  1254. type GetGrampusJobResponse struct {
  1255. GrampusResult
  1256. JobInfo GrampusJobInfo `json:"otJob"`
  1257. }
  1258. type GrampusStopJobResponse struct {
  1259. GrampusResult
  1260. StoppedAt int64 `json:"stoppedAt"`
  1261. }
  1262. type GrampusTasks struct {
  1263. Command string `json:"command"`
  1264. Name string `json:"name"`
  1265. ImageId string `json:"imageId"`
  1266. ResourceSpecId string `json:"resourceSpecId"`
  1267. ImageUrl string `json:"imageUrl"`
  1268. CenterID []string `json:"centerID"`
  1269. CenterName []string `json:"centerName"`
  1270. ReplicaNum int `json:"replicaNum"`
  1271. }
  1272. type CreateGrampusJobRequest struct {
  1273. Name string `json:"name"`
  1274. Tasks []GrampusTasks `json:"tasks"`
  1275. }
  1276. type GetTrainJobMetricStatisticResult struct {
  1277. TrainJobResult
  1278. Interval int `json:"interval"` //查询的时间间隔,单位为分钟
  1279. MetricsInfo []Metrics `json:"metrics"` //监控详情
  1280. }
  1281. type Metrics struct {
  1282. Metric string `json:"metric"` //监控指标项
  1283. Value []string `json:"value"` //获取的监控值的序列,元素为String类型
  1284. }
  1285. func Cloudbrains(opts *CloudbrainsOptions) ([]*CloudbrainInfo, int64, error) {
  1286. sess := x.NewSession()
  1287. defer sess.Close()
  1288. var cond = builder.NewCond()
  1289. if opts.RepoID > 0 {
  1290. cond = cond.And(
  1291. builder.Eq{"cloudbrain.repo_id": opts.RepoID},
  1292. )
  1293. }
  1294. if opts.UserID > 0 {
  1295. cond = cond.And(
  1296. builder.Eq{"cloudbrain.user_id": opts.UserID},
  1297. )
  1298. }
  1299. if (opts.JobID) != "" {
  1300. cond = cond.And(
  1301. builder.Eq{"cloudbrain.job_id": opts.JobID},
  1302. )
  1303. }
  1304. if (opts.ComputeResource) != "" {
  1305. cond = cond.And(
  1306. builder.Eq{"cloudbrain.compute_resource": opts.ComputeResource},
  1307. )
  1308. }
  1309. if (opts.Type) >= 0 {
  1310. cond = cond.And(
  1311. builder.Eq{"cloudbrain.type": opts.Type},
  1312. )
  1313. }
  1314. if len(opts.JobTypes) > 0 {
  1315. if opts.JobTypeNot {
  1316. cond = cond.And(
  1317. builder.NotIn("cloudbrain.job_type", opts.JobTypes),
  1318. )
  1319. } else {
  1320. cond = cond.And(
  1321. builder.In("cloudbrain.job_type", opts.JobTypes),
  1322. )
  1323. }
  1324. }
  1325. if (opts.AiCenter) != "" {
  1326. cond = cond.And(
  1327. builder.Like{"cloudbrain.ai_center", opts.AiCenter},
  1328. )
  1329. }
  1330. if (opts.Cluster) != "" {
  1331. if opts.Cluster == "resource_cluster_openi" {
  1332. cond = cond.And(
  1333. builder.Or(builder.Eq{"cloudbrain.type": TypeCloudBrainOne}, builder.Eq{"cloudbrain.type": TypeCloudBrainTwo}, builder.Eq{"cloudbrain.type": TypeCDCenter}),
  1334. )
  1335. }
  1336. if opts.Cluster == "resource_cluster_c2net" {
  1337. cond = cond.And(
  1338. builder.Eq{"cloudbrain.type": TypeC2Net},
  1339. )
  1340. }
  1341. }
  1342. if (opts.IsLatestVersion) != "" {
  1343. cond = cond.And(builder.Or(builder.And(builder.Eq{"cloudbrain.is_latest_version": opts.IsLatestVersion}, builder.Eq{"cloudbrain.job_type": "TRAIN"}), builder.Neq{"cloudbrain.job_type": "TRAIN"}))
  1344. }
  1345. if len(opts.CloudbrainIDs) > 0 {
  1346. cond = cond.And(builder.In("cloudbrain.id", opts.CloudbrainIDs))
  1347. }
  1348. if len(opts.JobStatus) > 0 {
  1349. if opts.JobStatusNot {
  1350. cond = cond.And(
  1351. builder.NotIn("cloudbrain.status", opts.JobStatus),
  1352. )
  1353. } else {
  1354. cond = cond.And(
  1355. builder.In("cloudbrain.status", opts.JobStatus),
  1356. )
  1357. }
  1358. }
  1359. if len(opts.RepoIDList) > 0 {
  1360. cond = cond.And(
  1361. builder.In("cloudbrain.repo_id", opts.RepoIDList),
  1362. )
  1363. }
  1364. var count int64
  1365. var err error
  1366. condition := "cloudbrain.user_id = `user`.id"
  1367. if len(opts.Keyword) == 0 {
  1368. count, err = sess.Where(cond).Count(new(Cloudbrain))
  1369. } else {
  1370. lowerKeyWord := strings.ToLower(opts.Keyword)
  1371. cond = cond.And(builder.Or(builder.Like{"LOWER(cloudbrain.job_name)", lowerKeyWord}, builder.Like{"LOWER(cloudbrain.display_job_name)", lowerKeyWord}, builder.Like{"`user`.lower_name", lowerKeyWord}))
  1372. count, err = sess.Table(&Cloudbrain{}).Where(cond).
  1373. Join("left", "`user`", condition).Count(new(CloudbrainInfo))
  1374. }
  1375. if err != nil {
  1376. return nil, 0, fmt.Errorf("Count: %v", err)
  1377. }
  1378. if opts.Page >= 0 && opts.PageSize > 0 {
  1379. var start int
  1380. if opts.Page == 0 {
  1381. start = 0
  1382. } else {
  1383. start = (opts.Page - 1) * opts.PageSize
  1384. }
  1385. sess.Limit(opts.PageSize, start)
  1386. }
  1387. sess.OrderBy("cloudbrain.created_unix DESC")
  1388. cloudbrains := make([]*CloudbrainInfo, 0, setting.UI.IssuePagingNum)
  1389. if err := sess.Table(&Cloudbrain{}).Where(cond).
  1390. Join("left", "`user`", condition).
  1391. Find(&cloudbrains); err != nil {
  1392. return nil, 0, fmt.Errorf("Find: %v", err)
  1393. }
  1394. if opts.NeedRepoInfo {
  1395. var ids []int64
  1396. for _, task := range cloudbrains {
  1397. ids = append(ids, task.RepoID)
  1398. }
  1399. repositoryMap, err := GetRepositoriesMapByIDs(ids)
  1400. if err == nil {
  1401. for _, task := range cloudbrains {
  1402. task.Repo = repositoryMap[task.RepoID]
  1403. }
  1404. }
  1405. }
  1406. return cloudbrains, count, nil
  1407. }
  1408. func QueryModelTrainJobVersionList(jobId string) ([]*Cloudbrain, int, error) {
  1409. sess := x.NewSession()
  1410. defer sess.Close()
  1411. var cond = builder.NewCond()
  1412. cond = cond.And(
  1413. builder.Eq{"cloudbrain.job_id": jobId},
  1414. )
  1415. cond = cond.And(
  1416. builder.In("cloudbrain.Status", "COMPLETED", "SUCCEEDED"),
  1417. //builder.Eq{"cloudbrain.Status": "COMPLETED"},
  1418. )
  1419. sess.OrderBy("cloudbrain.created_unix DESC")
  1420. cloudbrains := make([]*Cloudbrain, 0)
  1421. if err := sess.Table(&Cloudbrain{}).Where(cond).
  1422. Find(&cloudbrains); err != nil {
  1423. return nil, 0, fmt.Errorf("Find: %v", err)
  1424. }
  1425. return cloudbrains, int(len(cloudbrains)), nil
  1426. }
  1427. func QueryModelTrainJobList(repoId int64) ([]*CloudbrainInfo, int, error) {
  1428. sess := x.NewSession()
  1429. defer sess.Close()
  1430. var cond = builder.NewCond()
  1431. cond = cond.And(
  1432. builder.Eq{"repo_id": repoId},
  1433. )
  1434. cond = cond.And(
  1435. builder.In("Status", "COMPLETED", "SUCCEEDED"),
  1436. )
  1437. cond = cond.And(
  1438. builder.Eq{"job_type": "TRAIN"},
  1439. )
  1440. // cond = cond.And(
  1441. // builder.In("type", 0, 1),
  1442. // )
  1443. cloudbrains := make([]*CloudbrainInfo, 0)
  1444. if err := sess.Select("job_id,display_job_name").Table(&Cloudbrain{}).Where(cond).OrderBy("created_unix DESC").
  1445. Find(&cloudbrains); err != nil {
  1446. return nil, 0, fmt.Errorf("Find: %v", err)
  1447. }
  1448. keys := make(map[string]string)
  1449. uniqueElements := make([]*CloudbrainInfo, 0)
  1450. for _, entry := range cloudbrains {
  1451. if _, value := keys[entry.JobID]; !value {
  1452. keys[entry.JobID] = entry.DisplayJobName
  1453. uniqueElements = append(uniqueElements, entry)
  1454. }
  1455. }
  1456. return uniqueElements, int(len(uniqueElements)), nil
  1457. }
  1458. func CloudbrainsVersionList(opts *CloudbrainsOptions) ([]*CloudbrainInfo, int, error) {
  1459. sess := x.NewSession()
  1460. defer sess.Close()
  1461. var cond = builder.NewCond()
  1462. if opts.RepoID > 0 {
  1463. cond = cond.And(
  1464. builder.Eq{"cloudbrain.repo_id": opts.RepoID},
  1465. )
  1466. }
  1467. if opts.UserID > 0 {
  1468. cond = cond.And(
  1469. builder.Eq{"cloudbrain.user_id": opts.UserID},
  1470. )
  1471. }
  1472. if (opts.Type) >= 0 {
  1473. cond = cond.And(
  1474. builder.Eq{"cloudbrain.type": opts.Type},
  1475. )
  1476. }
  1477. if (opts.JobID) != "" {
  1478. cond = cond.And(
  1479. builder.Eq{"cloudbrain.job_id": opts.JobID},
  1480. )
  1481. }
  1482. if len(opts.JobTypes) > 0 {
  1483. cond = cond.And(
  1484. builder.In("cloudbrain.job_type", opts.JobTypes),
  1485. )
  1486. }
  1487. if len(opts.CloudbrainIDs) > 0 {
  1488. cond = cond.And(builder.In("cloudbrain.id", opts.CloudbrainIDs))
  1489. }
  1490. count, err := sess.Where(cond).Count(new(Cloudbrain))
  1491. if err != nil {
  1492. return nil, 0, fmt.Errorf("Count: %v", err)
  1493. }
  1494. if opts.Page >= 0 && opts.PageSize > 0 {
  1495. var start int
  1496. if opts.Page == 0 {
  1497. start = 0
  1498. } else {
  1499. start = (opts.Page - 1) * opts.PageSize
  1500. }
  1501. sess.Limit(opts.PageSize, start)
  1502. }
  1503. sess.OrderBy("cloudbrain.created_unix DESC")
  1504. cloudbrains := make([]*CloudbrainInfo, 0, setting.UI.IssuePagingNum)
  1505. if err := sess.Table(&Cloudbrain{}).Where(cond).
  1506. Join("left", "`user`", "cloudbrain.user_id = `user`.id").
  1507. Find(&cloudbrains); err != nil {
  1508. return nil, 0, fmt.Errorf("Find: %v", err)
  1509. }
  1510. return cloudbrains, int(count), nil
  1511. }
  1512. func CreateCloudbrain(cloudbrain *Cloudbrain) (err error) {
  1513. session := x.NewSession()
  1514. defer session.Close()
  1515. err = session.Begin()
  1516. cloudbrain.TrainJobDuration = DURATION_STR_ZERO
  1517. if _, err = session.NoAutoTime().InsertOne(cloudbrain); err != nil {
  1518. session.Rollback()
  1519. return err
  1520. }
  1521. if cloudbrain.Spec != nil {
  1522. if _, err = session.Insert(NewCloudBrainSpec(cloudbrain.ID, *cloudbrain.Spec)); err != nil {
  1523. session.Rollback()
  1524. return err
  1525. }
  1526. }
  1527. session.Commit()
  1528. go IncreaseDatasetUseCount(cloudbrain.Uuid)
  1529. return nil
  1530. }
  1531. func getRepoCloudBrain(cb *Cloudbrain) (*Cloudbrain, error) {
  1532. has, err := x.Get(cb)
  1533. if err != nil {
  1534. return nil, err
  1535. } else if !has {
  1536. return nil, ErrJobNotExist{}
  1537. }
  1538. return cb, nil
  1539. }
  1540. func getRepoCloudBrainWithDeleted(cb *Cloudbrain) (*Cloudbrain, error) {
  1541. has, err := x.Unscoped().Get(cb)
  1542. if err != nil {
  1543. return nil, err
  1544. } else if !has {
  1545. return nil, ErrJobNotExist{}
  1546. }
  1547. return cb, nil
  1548. }
  1549. func GetRepoCloudBrainByJobID(repoID int64, jobID string) (*Cloudbrain, error) {
  1550. cb := &Cloudbrain{JobID: jobID, RepoID: repoID}
  1551. return getRepoCloudBrain(cb)
  1552. }
  1553. func GetCloudbrainByJobID(jobID string) (*Cloudbrain, error) {
  1554. cb := &Cloudbrain{JobID: jobID}
  1555. return getRepoCloudBrain(cb)
  1556. }
  1557. func GetCloudbrainByJobIDWithDeleted(jobID string) (*Cloudbrain, error) {
  1558. cb := &Cloudbrain{JobID: jobID}
  1559. return getRepoCloudBrainWithDeleted(cb)
  1560. }
  1561. func GetCloudbrainByID(id string) (*Cloudbrain, error) {
  1562. idInt64, _ := strconv.ParseInt(id, 10, 64)
  1563. cb := &Cloudbrain{ID: idInt64}
  1564. return getRepoCloudBrain(cb)
  1565. }
  1566. func GetCloudbrainByIDWithDeleted(id string) (*Cloudbrain, error) {
  1567. idInt64, _ := strconv.ParseInt(id, 10, 64)
  1568. cb := &Cloudbrain{ID: idInt64}
  1569. return getRepoCloudBrainWithDeleted(cb)
  1570. }
  1571. func GetCloudbrainByJobIDAndVersionName(jobID string, versionName string) (*Cloudbrain, error) {
  1572. cb := &Cloudbrain{JobID: jobID, VersionName: versionName}
  1573. return getRepoCloudBrain(cb)
  1574. }
  1575. func GetCloudbrainByJobIDAndIsLatestVersion(jobID string, isLatestVersion string) (*Cloudbrain, error) {
  1576. cb := &Cloudbrain{JobID: jobID, IsLatestVersion: isLatestVersion}
  1577. return getRepoCloudBrain(cb)
  1578. }
  1579. func GetCloudbrainsNeededStopByUserID(userID int64) ([]*Cloudbrain, error) {
  1580. cloudBrains := make([]*Cloudbrain, 0)
  1581. err := x.Cols("job_id", "status", "type", "job_type", "version_id", "start_time").Where("user_id=? AND status !=?", userID, string(JobStopped)).Find(&cloudBrains)
  1582. return cloudBrains, err
  1583. }
  1584. func GetModelartsReDebugTaskByJobId(jobID string) ([]*Cloudbrain, error) {
  1585. sess := x.NewSession()
  1586. defer sess.Close()
  1587. var cond = builder.NewCond()
  1588. cond = cond.And(
  1589. builder.Eq{"cloudbrain.job_id": jobID},
  1590. )
  1591. sess.OrderBy("cloudbrain.created_unix ASC limit 1")
  1592. cloudbrains := make([]*Cloudbrain, 0, 10)
  1593. if err := sess.Table(&Cloudbrain{}).Unscoped().Where(cond).
  1594. Find(&cloudbrains); err != nil {
  1595. log.Info("find error.")
  1596. }
  1597. return cloudbrains, nil
  1598. }
  1599. func GetCloudbrainsNeededStopByRepoID(repoID int64) ([]*Cloudbrain, error) {
  1600. cloudBrains := make([]*Cloudbrain, 0)
  1601. err := x.Cols("job_id", "status", "type", "job_type", "version_id", "start_time").Where("repo_id=? AND status !=?", repoID, string(JobStopped)).Find(&cloudBrains)
  1602. return cloudBrains, err
  1603. }
  1604. func GetCloudbrainsNeededDeleteByRepoID(repoID int64) ([]*Cloudbrain, error) {
  1605. cloudBrains := make([]*Cloudbrain, 0)
  1606. err := x.Where("repo_id=?", repoID).Find(&cloudBrains)
  1607. return cloudBrains, err
  1608. }
  1609. func GetCloudbrainsByDisplayJobName(repoID int64, jobType string, displayJobName string) ([]*Cloudbrain, error) {
  1610. cloudBrains := make([]*Cloudbrain, 0)
  1611. err := x.Cols("job_id", "job_name", "repo_id", "user_id", "job_type", "display_job_name").Where("repo_id=? AND job_type =? AND lower(display_job_name) = lower(?)", repoID, jobType, displayJobName).Find(&cloudBrains)
  1612. return cloudBrains, err
  1613. }
  1614. func SetCloudbrainStatusByJobID(jobID string, status CloudbrainStatus) (err error) {
  1615. cb := &Cloudbrain{JobID: jobID, Status: string(status)}
  1616. _, err = x.Cols("status").Where("cloudbrain.job_id=?", jobID).Update(cb)
  1617. return
  1618. }
  1619. func SetTrainJobStatusByJobID(jobID string, status string, duration int64, trainjobduration string) (err error) {
  1620. cb := &Cloudbrain{JobID: jobID, Status: string(status), Duration: duration, TrainJobDuration: trainjobduration}
  1621. _, err = x.Cols("status", "duration", "train_job_duration").Where("cloudbrain.job_id=?", jobID).Update(cb)
  1622. return
  1623. }
  1624. func SetVersionCountAndLatestVersion(jobID string, versionName string, versionCount int, isLatestVersion string, totalVersionCount int) (err error) {
  1625. cb := &Cloudbrain{JobID: jobID, VersionName: versionName, VersionCount: versionCount, IsLatestVersion: isLatestVersion, TotalVersionCount: totalVersionCount}
  1626. _, err = x.Cols("version_Count", "is_latest_version", "total_version_count").Where("cloudbrain.job_id=? AND cloudbrain.version_name=?", jobID, versionName).Update(cb)
  1627. return
  1628. }
  1629. func UpdateJob(job *Cloudbrain) error {
  1630. return updateJob(x, job)
  1631. }
  1632. func UpdateJobDurationWithDeleted(job *Cloudbrain) error {
  1633. _, err := x.Exec("update cloudbrain set start_time=?, end_time=?,train_job_duration=?,duration=? where id=?", job.StartTime, job.EndTime, job.TrainJobDuration, job.Duration, job.ID)
  1634. return err
  1635. }
  1636. func updateJob(e Engine, job *Cloudbrain) error {
  1637. _, err := e.ID(job.ID).AllCols().Update(job)
  1638. return err
  1639. }
  1640. func UpdateTrainJobVersion(job *Cloudbrain) error {
  1641. return updateJobTrainVersion(x, job)
  1642. }
  1643. func updateJobTrainVersion(e Engine, job *Cloudbrain) error {
  1644. var sess *xorm.Session
  1645. sess = e.Where("job_id = ? AND version_name=?", job.JobID, job.VersionName)
  1646. _, err := sess.Cols("status", "train_job_duration", "duration", "start_time", "end_time", "created_unix").Update(job)
  1647. return err
  1648. }
  1649. func DeleteJob(job *Cloudbrain) error {
  1650. return deleteJob(x, job)
  1651. }
  1652. func deleteJob(e Engine, job *Cloudbrain) error {
  1653. _, err := e.ID(job.ID).Delete(job)
  1654. return err
  1655. }
  1656. func GetCloudbrainByName(jobName string) (*Cloudbrain, error) {
  1657. cb := &Cloudbrain{JobName: jobName}
  1658. return getRepoCloudBrain(cb)
  1659. }
  1660. func CanDelJob(isSigned bool, user *User, job *CloudbrainInfo) bool {
  1661. if !isSigned || (job.Status != string(JobStopped) && job.Status != string(JobFailed) && job.Status != string(ModelArtsStartFailed) && job.Status != string(ModelArtsCreateFailed)) {
  1662. return false
  1663. }
  1664. repo, err := GetRepositoryByID(job.RepoID)
  1665. if err != nil {
  1666. log.Error("GetRepositoryByID failed:%v", err.Error())
  1667. return false
  1668. }
  1669. permission, _ := GetUserRepoPermission(repo, user)
  1670. if err != nil {
  1671. log.Error("GetUserRepoPermission failed:%v", err.Error())
  1672. return false
  1673. }
  1674. if (user.ID == job.UserID && permission.AccessMode >= AccessModeWrite) || user.IsAdmin || permission.AccessMode >= AccessModeAdmin {
  1675. return true
  1676. }
  1677. return false
  1678. }
  1679. func GetCloudBrainUnStoppedJob() ([]*Cloudbrain, error) {
  1680. cloudbrains := make([]*Cloudbrain, 0, 10)
  1681. return cloudbrains, x.
  1682. NotIn("status",
  1683. JobStopped, JobSucceeded, JobFailed, ModelArtsCreateFailed, ModelArtsStartFailed, ModelArtsUnavailable, ModelArtsResizFailed, ModelArtsDeleted,
  1684. ModelArtsStopped, ModelArtsTrainJobCanceled, ModelArtsTrainJobCheckFailed, ModelArtsTrainJobCompleted, ModelArtsTrainJobDeleteFailed, ModelArtsTrainJobDeployServiceFailed,
  1685. ModelArtsTrainJobFailed, ModelArtsTrainJobImageFailed, ModelArtsTrainJobKilled, ModelArtsTrainJobLost, ModelArtsTrainJobSubmitFailed, ModelArtsTrainJobSubmitModelFailed).
  1686. Limit(100).
  1687. Find(&cloudbrains)
  1688. }
  1689. func GetStoppedJobWithNoDurationJob() ([]*Cloudbrain, error) {
  1690. cloudbrains := make([]*Cloudbrain, 0)
  1691. return cloudbrains, x.
  1692. In("status", ModelArtsTrainJobCompleted, ModelArtsTrainJobFailed, ModelArtsTrainJobKilled, ModelArtsStopped, JobStopped, JobFailed, JobSucceeded).
  1693. Where("train_job_duration is null or train_job_duration = '' ").
  1694. Limit(100).
  1695. Find(&cloudbrains)
  1696. }
  1697. func GetStoppedJobWithNoStartTimeEndTime() ([]*Cloudbrain, error) {
  1698. cloudbrains := make([]*Cloudbrain, 0)
  1699. return cloudbrains, x.SQL("select * from cloudbrain where status in (?,?,?,?,?,?,?) and (start_time is null or end_time is null) limit 100", ModelArtsTrainJobCompleted, ModelArtsTrainJobFailed, ModelArtsTrainJobKilled, ModelArtsStopped, JobStopped, JobFailed, JobSucceeded).Find(&cloudbrains)
  1700. }
  1701. func GetCloudbrainCountByUserID(userID int64, jobType string) (int, error) {
  1702. count, err := x.In("status", JobWaiting, JobRunning).And("job_type = ? and user_id = ? and type = ?", jobType, userID, TypeCloudBrainOne).Count(new(Cloudbrain))
  1703. return int(count), err
  1704. }
  1705. func GetCloudbrainRunCountByRepoID(repoID int64) (int, error) {
  1706. count, err := x.In("status", JobWaiting, JobRunning, ModelArtsCreateQueue, ModelArtsCreating, ModelArtsStarting,
  1707. ModelArtsReadyToStart, ModelArtsResizing, ModelArtsStartQueuing, ModelArtsRunning, ModelArtsDeleting, ModelArtsRestarting, ModelArtsTrainJobInit,
  1708. ModelArtsTrainJobImageCreating, ModelArtsTrainJobSubmitTrying, ModelArtsTrainJobWaiting, ModelArtsTrainJobRunning, ModelArtsStopping, ModelArtsResizing,
  1709. ModelArtsTrainJobScaling, ModelArtsTrainJobCheckInit, ModelArtsTrainJobCheckRunning, ModelArtsTrainJobKilling, ModelArtsTrainJobCheckRunningCompleted).And("repo_id = ?", repoID).Count(new(Cloudbrain))
  1710. return int(count), err
  1711. }
  1712. func GetBenchmarkCountByUserID(userID int64) (int, error) {
  1713. count, err := x.In("status", JobWaiting, JobRunning).And("(job_type = ? or job_type = ? or job_type = ?) and user_id = ? and type = ?", string(JobTypeBenchmark), string(JobTypeBrainScore), string(JobTypeSnn4imagenet), userID, TypeCloudBrainOne).Count(new(Cloudbrain))
  1714. return int(count), err
  1715. }
  1716. func GetWaitingCloudbrainCount(cloudbrainType int, computeResource string, jobTypes ...JobType) (int64, error) {
  1717. sess := x.Where("status=? and type=?", JobWaiting, cloudbrainType)
  1718. if len(jobTypes) > 0 {
  1719. sess.In("job_type", jobTypes)
  1720. }
  1721. if computeResource != "" {
  1722. sess.And("compute_resource=?", computeResource)
  1723. }
  1724. return sess.Count(new(Cloudbrain))
  1725. }
  1726. func GetCloudbrainNotebookCountByUserID(userID int64) (int, error) {
  1727. count, err := x.In("status", ModelArtsCreateQueue, ModelArtsCreating, ModelArtsStarting, ModelArtsReadyToStart, ModelArtsResizing, ModelArtsStartQueuing, ModelArtsRunning, ModelArtsRestarting).
  1728. And("job_type = ? and user_id = ? and type in (?,?)", JobTypeDebug, userID, TypeCloudBrainTwo, TypeCDCenter).Count(new(Cloudbrain))
  1729. return int(count), err
  1730. }
  1731. func GetCloudbrainTrainJobCountByUserID(userID int64) (int, error) {
  1732. count, err := x.In("status", ModelArtsTrainJobInit, ModelArtsTrainJobImageCreating, ModelArtsTrainJobSubmitTrying, ModelArtsTrainJobWaiting, ModelArtsTrainJobRunning, ModelArtsTrainJobScaling, ModelArtsTrainJobCheckInit, ModelArtsTrainJobCheckRunning, ModelArtsTrainJobCheckRunningCompleted).
  1733. And("job_type = ? and user_id = ? and type = ?", JobTypeTrain, userID, TypeCloudBrainTwo).Count(new(Cloudbrain))
  1734. return int(count), err
  1735. }
  1736. func GetCloudbrainInferenceJobCountByUserID(userID int64) (int, error) {
  1737. count, err := x.In("status", ModelArtsTrainJobInit, ModelArtsTrainJobImageCreating, ModelArtsTrainJobSubmitTrying, ModelArtsTrainJobWaiting, ModelArtsTrainJobRunning, ModelArtsTrainJobScaling, ModelArtsTrainJobCheckInit, ModelArtsTrainJobCheckRunning, ModelArtsTrainJobCheckRunningCompleted).
  1738. And("job_type = ? and user_id = ? and type = ?", JobTypeInference, userID, TypeCloudBrainTwo).Count(new(Cloudbrain))
  1739. return int(count), err
  1740. }
  1741. func GetGrampusCountByUserID(userID int64, jobType, computeResource string) (int, error) {
  1742. count, err := x.In("status", GrampusStatusWaiting, GrampusStatusRunning).And("job_type = ? and user_id = ? and type = ?", jobType, userID, TypeC2Net).And("compute_resource = ?", computeResource).Count(new(Cloudbrain))
  1743. return int(count), err
  1744. }
  1745. func UpdateInferenceJob(job *Cloudbrain) error {
  1746. return updateInferenceJob(x, job)
  1747. }
  1748. func updateInferenceJob(e Engine, job *Cloudbrain) error {
  1749. var sess *xorm.Session
  1750. sess = e.Where("job_id = ?", job.JobID)
  1751. _, err := sess.Cols("status", "train_job_duration", "duration", "start_time", "end_time", "created_unix").Update(job)
  1752. return err
  1753. }
  1754. func RestartCloudbrain(old *Cloudbrain, new *Cloudbrain) (err error) {
  1755. sess := x.NewSession()
  1756. defer sess.Close()
  1757. if err = sess.Begin(); err != nil {
  1758. return err
  1759. }
  1760. if _, err = sess.Delete(old); err != nil {
  1761. sess.Rollback()
  1762. return err
  1763. }
  1764. if _, err = sess.NoAutoTime().InsertOne(new); err != nil {
  1765. sess.Rollback()
  1766. return err
  1767. }
  1768. if new.Spec != nil {
  1769. if _, err = sess.Insert(NewCloudBrainSpec(new.ID, *new.Spec)); err != nil {
  1770. sess.Rollback()
  1771. return err
  1772. }
  1773. }
  1774. if err = sess.Commit(); err != nil {
  1775. return err
  1776. }
  1777. go IncreaseDatasetUseCount(new.Uuid)
  1778. return nil
  1779. }
  1780. func CloudbrainAll(opts *CloudbrainsOptions) ([]*CloudbrainInfo, int64, error) {
  1781. sess := x.NewSession()
  1782. defer sess.Close()
  1783. var cond = builder.NewCond()
  1784. if opts.RepoID > 0 {
  1785. cond = cond.And(
  1786. builder.Eq{"cloudbrain.repo_id": opts.RepoID},
  1787. )
  1788. }
  1789. if opts.UserID > 0 {
  1790. cond = cond.And(
  1791. builder.Eq{"cloudbrain.user_id": opts.UserID},
  1792. )
  1793. }
  1794. if (opts.JobID) != "" {
  1795. cond = cond.And(
  1796. builder.Eq{"cloudbrain.job_id": opts.JobID},
  1797. )
  1798. }
  1799. if (opts.ComputeResource) != "" {
  1800. cond = cond.And(
  1801. builder.Eq{"cloudbrain.compute_resource": opts.ComputeResource},
  1802. )
  1803. }
  1804. if (opts.Type) >= 0 {
  1805. cond = cond.And(
  1806. builder.Eq{"cloudbrain.type": opts.Type},
  1807. )
  1808. }
  1809. if len(opts.JobTypes) > 0 {
  1810. if opts.JobTypeNot {
  1811. cond = cond.And(
  1812. builder.NotIn("cloudbrain.job_type", opts.JobTypes),
  1813. )
  1814. } else {
  1815. cond = cond.And(
  1816. builder.In("cloudbrain.job_type", opts.JobTypes),
  1817. )
  1818. }
  1819. }
  1820. if (opts.AiCenter) != "" {
  1821. cond = cond.And(
  1822. builder.Like{"cloudbrain.ai_center", opts.AiCenter},
  1823. )
  1824. }
  1825. if (opts.NeedDeleteInfo) != "" {
  1826. if opts.NeedDeleteInfo == "yes" {
  1827. cond = cond.And(
  1828. builder.And(builder.NotNull{"cloudbrain.deleted_at"}),
  1829. )
  1830. }
  1831. if opts.NeedDeleteInfo == "no" {
  1832. cond = cond.And(
  1833. builder.And(builder.IsNull{"cloudbrain.deleted_at"}),
  1834. )
  1835. }
  1836. }
  1837. if (opts.IsLatestVersion) != "" {
  1838. cond = cond.And(builder.Or(builder.And(builder.Eq{"cloudbrain.is_latest_version": opts.IsLatestVersion},
  1839. builder.Eq{"cloudbrain.job_type": "TRAIN"}), builder.Neq{"cloudbrain.job_type": "TRAIN"}))
  1840. }
  1841. if len(opts.CloudbrainIDs) > 0 {
  1842. cond = cond.And(builder.In("cloudbrain.id", opts.CloudbrainIDs))
  1843. }
  1844. if len(opts.JobStatus) > 0 {
  1845. if opts.JobStatusNot {
  1846. cond = cond.And(
  1847. builder.NotIn("cloudbrain.status", opts.JobStatus),
  1848. )
  1849. } else {
  1850. cond = cond.And(
  1851. builder.In("cloudbrain.status", opts.JobStatus),
  1852. )
  1853. }
  1854. }
  1855. if len(opts.RepoIDList) > 0 {
  1856. cond = cond.And(
  1857. builder.In("cloudbrain.repo_id", opts.RepoIDList),
  1858. )
  1859. }
  1860. if opts.BeginTimeUnix > 0 && opts.EndTimeUnix > 0 {
  1861. cond = cond.And(
  1862. builder.And(builder.Gte{"cloudbrain.created_unix": opts.BeginTimeUnix}, builder.Lte{"cloudbrain.created_unix": opts.EndTimeUnix}),
  1863. )
  1864. }
  1865. var count int64
  1866. var err error
  1867. condition := "cloudbrain.user_id = `user`.id"
  1868. if len(opts.Keyword) == 0 {
  1869. count, err = sess.Unscoped().Where(cond).Count(new(Cloudbrain))
  1870. } else {
  1871. lowerKeyWord := strings.ToLower(opts.Keyword)
  1872. cond = cond.And(builder.Or(builder.Like{"LOWER(cloudbrain.job_name)", lowerKeyWord},
  1873. builder.Like{"LOWER(cloudbrain.display_job_name)", lowerKeyWord}, builder.Like{"`user`.lower_name", lowerKeyWord}))
  1874. count, err = sess.Table(&Cloudbrain{}).Unscoped().Where(cond).
  1875. Join("left", "`user`", condition).Count(new(CloudbrainInfo))
  1876. }
  1877. if err != nil {
  1878. return nil, 0, fmt.Errorf("Count: %v", err)
  1879. }
  1880. if opts.Page >= 0 && opts.PageSize > 0 {
  1881. var start int
  1882. if opts.Page == 0 {
  1883. start = 0
  1884. } else {
  1885. start = (opts.Page - 1) * opts.PageSize
  1886. }
  1887. sess.Limit(opts.PageSize, start)
  1888. }
  1889. sess.OrderBy("cloudbrain.created_unix DESC")
  1890. cloudbrains := make([]*CloudbrainInfo, 0, setting.UI.IssuePagingNum)
  1891. if err := sess.Table(&Cloudbrain{}).Unscoped().Where(cond).
  1892. Join("left", "`user`", condition).
  1893. Find(&cloudbrains); err != nil {
  1894. return nil, 0, fmt.Errorf("Find: %v", err)
  1895. }
  1896. if opts.NeedRepoInfo {
  1897. var ids []int64
  1898. for _, task := range cloudbrains {
  1899. ids = append(ids, task.RepoID)
  1900. }
  1901. repositoryMap, err := GetRepositoriesMapByIDs(ids)
  1902. if err == nil {
  1903. for _, task := range cloudbrains {
  1904. task.Repo = repositoryMap[task.RepoID]
  1905. }
  1906. }
  1907. }
  1908. return cloudbrains, count, nil
  1909. }
  1910. func CloudbrainAllStatic(opts *CloudbrainsOptions) ([]*CloudbrainInfo, int64, error) {
  1911. sess := x.NewSession()
  1912. defer sess.Close()
  1913. var cond = builder.NewCond()
  1914. if (opts.Type) >= 0 {
  1915. cond = cond.And(
  1916. builder.Eq{"cloudbrain.type": opts.Type},
  1917. )
  1918. }
  1919. if opts.BeginTimeUnix > 0 && opts.EndTimeUnix > 0 {
  1920. cond = cond.And(
  1921. builder.And(builder.Gte{"cloudbrain.created_unix": opts.BeginTimeUnix}, builder.Lte{"cloudbrain.created_unix": opts.EndTimeUnix}),
  1922. )
  1923. }
  1924. var count int64
  1925. var err error
  1926. count, err = sess.Unscoped().Where(cond).Count(new(Cloudbrain))
  1927. if err != nil {
  1928. return nil, 0, fmt.Errorf("Count: %v", err)
  1929. }
  1930. if opts.Page >= 0 && opts.PageSize > 0 {
  1931. var start int
  1932. if opts.Page == 0 {
  1933. start = 0
  1934. } else {
  1935. start = (opts.Page - 1) * opts.PageSize
  1936. }
  1937. sess.Limit(opts.PageSize, start)
  1938. }
  1939. sess.OrderBy("cloudbrain.created_unix DESC")
  1940. cloudbrains := make([]*CloudbrainInfo, 0, setting.UI.IssuePagingNum)
  1941. if err := sess.Cols("status", "type", "job_type", "train_job_duration", "duration", "compute_resource",
  1942. "created_unix", "start_time", "end_time").Table(&Cloudbrain{}).Unscoped().Where(cond).
  1943. Find(&cloudbrains); err != nil {
  1944. return nil, 0, fmt.Errorf("Find: %v", err)
  1945. }
  1946. return cloudbrains, count, nil
  1947. }
  1948. type DatasetInfo struct {
  1949. DataLocalPath string
  1950. Name string
  1951. }
  1952. func GetDatasetInfo(uuidStr string) (map[string]DatasetInfo, string, error) {
  1953. var datasetNames string
  1954. uuids := strings.Split(uuidStr, ";")
  1955. if len(uuids) > setting.MaxDatasetNum {
  1956. log.Error("the dataset count(%d) exceed the limit", len(uuids))
  1957. return nil, datasetNames, errors.New("the dataset count exceed the limit")
  1958. }
  1959. datasetInfos := make(map[string]DatasetInfo)
  1960. attachs, err := GetAttachmentsByUUIDs(uuids)
  1961. if err != nil {
  1962. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  1963. return nil, datasetNames, err
  1964. }
  1965. for i, tmpUuid := range uuids {
  1966. var attach *Attachment
  1967. for _, tmpAttach := range attachs {
  1968. if tmpAttach.UUID == tmpUuid {
  1969. attach = tmpAttach
  1970. break
  1971. }
  1972. }
  1973. if attach == nil {
  1974. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  1975. return nil, datasetNames, err
  1976. }
  1977. fileName := strings.TrimSuffix(strings.TrimSuffix(strings.TrimSuffix(attach.Name, ".zip"), ".tar.gz"), ".tgz")
  1978. for _, datasetInfo := range datasetInfos {
  1979. if fileName == datasetInfo.Name {
  1980. log.Error("the dataset name is same: %v", attach.Name)
  1981. return nil, datasetNames, errors.New("the dataset name is same")
  1982. }
  1983. }
  1984. dataLocalPath := setting.Attachment.Minio.RealPath +
  1985. setting.Attachment.Minio.Bucket + "/" +
  1986. setting.Attachment.Minio.BasePath +
  1987. AttachmentRelativePath(attach.UUID) +
  1988. attach.UUID
  1989. datasetInfos[attach.UUID] = DatasetInfo{
  1990. DataLocalPath: dataLocalPath,
  1991. Name: fileName,
  1992. }
  1993. if i == 0 {
  1994. datasetNames = attach.Name
  1995. } else {
  1996. datasetNames += ";" + attach.Name
  1997. }
  1998. }
  1999. return datasetInfos, datasetNames, nil
  2000. }
  2001. var (
  2002. SpecsMapInitFlag = false
  2003. CloudbrainDebugResourceSpecsMap map[int]*ResourceSpec
  2004. CloudbrainTrainResourceSpecsMap map[int]*ResourceSpec
  2005. CloudbrainInferenceResourceSpecsMap map[int]*ResourceSpec
  2006. CloudbrainBenchmarkResourceSpecsMap map[int]*ResourceSpec
  2007. CloudbrainSpecialResourceSpecsMap map[int]*ResourceSpec
  2008. GpuInfosMapInitFlag = false
  2009. CloudbrainDebugGpuInfosMap map[string]*GpuInfo
  2010. CloudbrainTrainGpuInfosMap map[string]*GpuInfo
  2011. CloudbrainInferenceGpuInfosMap map[string]*GpuInfo
  2012. CloudbrainBenchmarkGpuInfosMap map[string]*GpuInfo
  2013. CloudbrainSpecialGpuInfosMap map[string]*GpuInfo
  2014. )
  2015. func InitCloudbrainOneResourceSpecMap() {
  2016. if CloudbrainDebugResourceSpecsMap == nil || len(CloudbrainDebugResourceSpecsMap) == 0 {
  2017. t := ResourceSpecs{}
  2018. json.Unmarshal([]byte(setting.ResourceSpecs), &t)
  2019. CloudbrainDebugResourceSpecsMap = make(map[int]*ResourceSpec, len(t.ResourceSpec))
  2020. for _, spec := range t.ResourceSpec {
  2021. CloudbrainDebugResourceSpecsMap[spec.Id] = spec
  2022. }
  2023. }
  2024. if CloudbrainTrainResourceSpecsMap == nil || len(CloudbrainTrainResourceSpecsMap) == 0 {
  2025. t := ResourceSpecs{}
  2026. json.Unmarshal([]byte(setting.TrainResourceSpecs), &t)
  2027. CloudbrainTrainResourceSpecsMap = make(map[int]*ResourceSpec, len(t.ResourceSpec))
  2028. for _, spec := range t.ResourceSpec {
  2029. CloudbrainTrainResourceSpecsMap[spec.Id] = spec
  2030. }
  2031. }
  2032. if CloudbrainInferenceResourceSpecsMap == nil || len(CloudbrainInferenceResourceSpecsMap) == 0 {
  2033. t := ResourceSpecs{}
  2034. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &t)
  2035. CloudbrainInferenceResourceSpecsMap = make(map[int]*ResourceSpec, len(t.ResourceSpec))
  2036. for _, spec := range t.ResourceSpec {
  2037. CloudbrainInferenceResourceSpecsMap[spec.Id] = spec
  2038. }
  2039. }
  2040. if CloudbrainBenchmarkResourceSpecsMap == nil || len(CloudbrainBenchmarkResourceSpecsMap) == 0 {
  2041. t := ResourceSpecs{}
  2042. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &t)
  2043. CloudbrainBenchmarkResourceSpecsMap = make(map[int]*ResourceSpec, len(t.ResourceSpec))
  2044. for _, spec := range t.ResourceSpec {
  2045. CloudbrainBenchmarkResourceSpecsMap[spec.Id] = spec
  2046. }
  2047. }
  2048. if CloudbrainSpecialResourceSpecsMap == nil || len(CloudbrainSpecialResourceSpecsMap) == 0 {
  2049. t := SpecialPools{}
  2050. json.Unmarshal([]byte(setting.SpecialPools), &t)
  2051. for _, pool := range t.Pools {
  2052. CloudbrainSpecialResourceSpecsMap = make(map[int]*ResourceSpec, len(pool.ResourceSpec))
  2053. for _, spec := range pool.ResourceSpec {
  2054. CloudbrainSpecialResourceSpecsMap[spec.Id] = spec
  2055. }
  2056. }
  2057. }
  2058. SpecsMapInitFlag = true
  2059. }
  2060. func InitCloudbrainOneGpuInfoMap() {
  2061. if CloudbrainDebugGpuInfosMap == nil || len(CloudbrainDebugGpuInfosMap) == 0 {
  2062. t := GpuInfos{}
  2063. json.Unmarshal([]byte(setting.GpuTypes), &t)
  2064. CloudbrainDebugGpuInfosMap = make(map[string]*GpuInfo, len(t.GpuInfo))
  2065. for _, GpuInfo := range t.GpuInfo {
  2066. CloudbrainDebugGpuInfosMap[GpuInfo.Queue] = GpuInfo
  2067. }
  2068. }
  2069. if CloudbrainTrainGpuInfosMap == nil || len(CloudbrainTrainGpuInfosMap) == 0 {
  2070. t := GpuInfos{}
  2071. json.Unmarshal([]byte(setting.TrainGpuTypes), &t)
  2072. CloudbrainTrainGpuInfosMap = make(map[string]*GpuInfo, len(t.GpuInfo))
  2073. for _, GpuInfo := range t.GpuInfo {
  2074. CloudbrainTrainGpuInfosMap[GpuInfo.Queue] = GpuInfo
  2075. }
  2076. }
  2077. if CloudbrainInferenceGpuInfosMap == nil || len(CloudbrainInferenceGpuInfosMap) == 0 {
  2078. t := GpuInfos{}
  2079. json.Unmarshal([]byte(setting.InferenceGpuTypes), &t)
  2080. CloudbrainInferenceGpuInfosMap = make(map[string]*GpuInfo, len(t.GpuInfo))
  2081. for _, GpuInfo := range t.GpuInfo {
  2082. CloudbrainInferenceGpuInfosMap[GpuInfo.Queue] = GpuInfo
  2083. }
  2084. }
  2085. if CloudbrainBenchmarkGpuInfosMap == nil || len(CloudbrainBenchmarkGpuInfosMap) == 0 {
  2086. t := GpuInfos{}
  2087. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &t)
  2088. CloudbrainBenchmarkGpuInfosMap = make(map[string]*GpuInfo, len(t.GpuInfo))
  2089. for _, GpuInfo := range t.GpuInfo {
  2090. CloudbrainBenchmarkGpuInfosMap[GpuInfo.Queue] = GpuInfo
  2091. }
  2092. }
  2093. if CloudbrainSpecialGpuInfosMap == nil || len(CloudbrainSpecialGpuInfosMap) == 0 {
  2094. t := SpecialPools{}
  2095. json.Unmarshal([]byte(setting.SpecialPools), &t)
  2096. for _, pool := range t.Pools {
  2097. CloudbrainSpecialGpuInfosMap = make(map[string]*GpuInfo, len(pool.Pool))
  2098. for _, GpuInfo := range pool.Pool {
  2099. CloudbrainSpecialGpuInfosMap[GpuInfo.Queue] = GpuInfo
  2100. }
  2101. }
  2102. }
  2103. GpuInfosMapInitFlag = true
  2104. }
  2105. func GetNewestJobsByAiCenter() ([]int64, error) {
  2106. ids := make([]int64, 0)
  2107. return ids, x.
  2108. Select("max(id) as id").
  2109. Where("type=? and ai_center!='' and ai_center is not null", TypeC2Net).
  2110. GroupBy("ai_center").
  2111. Table(Cloudbrain{}).
  2112. Find(&ids)
  2113. }
  2114. func GetNewestJobsByType() ([]int64, error) {
  2115. ids := make([]int64, 0)
  2116. return ids, x.
  2117. Select("max(id) as id").
  2118. In("type", TypeCloudBrainOne, TypeCloudBrainTwo).
  2119. GroupBy("type").
  2120. Table(Cloudbrain{}).
  2121. Find(&ids)
  2122. }
  2123. func GetCloudbrainByIDs(ids []int64) ([]*Cloudbrain, error) {
  2124. cloudbrains := make([]*Cloudbrain, 0)
  2125. return cloudbrains, x.
  2126. In("id", ids).
  2127. Find(&cloudbrains)
  2128. }
  2129. func GetCloudbrainWithDeletedByIDs(ids []int64) ([]*Cloudbrain, error) {
  2130. cloudbrains := make([]*Cloudbrain, 0)
  2131. return cloudbrains, x.
  2132. In("id", ids).Unscoped().Find(&cloudbrains)
  2133. }
  2134. func GetCloudbrainCountByJobName(jobName, jobType string, typeCloudbrain int) (int, error) {
  2135. count, err := x.Where("job_name = ? and job_type= ? and type = ?", jobName, jobType, typeCloudbrain).Count(new(Cloudbrain))
  2136. return int(count), err
  2137. }