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

cloudbrain.go 82 kB

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