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

5 years ago
5 years ago
5 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. package cloudbrain
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strconv"
  6. "code.gitea.io/gitea/modules/timeutil"
  7. "code.gitea.io/gitea/modules/storage"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/context"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/notification"
  12. "code.gitea.io/gitea/modules/setting"
  13. )
  14. const (
  15. Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"`
  16. //CommandBenchmark = `echo "start benchmark";python /code/test.py;echo "end benchmark"`
  17. CommandBenchmark = `echo "start benchmark";cd /benchmark && bash run_bk.sh;echo "end benchmark"`
  18. CodeMountPath = "/code"
  19. DataSetMountPath = "/dataset"
  20. ModelMountPath = "/model"
  21. LogFile = "log.txt"
  22. BenchMarkMountPath = "/benchmark"
  23. BenchMarkResourceID = 1
  24. Snn4imagenetMountPath = "/snn4imagenet"
  25. BrainScoreMountPath = "/brainscore"
  26. TaskInfoName = "/taskInfo"
  27. Snn4imagenetCommand = `/opt/conda/bin/python /snn4imagenet/testSNN_script.py --modelname '%s' --modelpath '/dataset' --modeldescription '%s'`
  28. BrainScoreCommand = `bash /brainscore/brainscore_test_par4shSrcipt.sh -b '%s' -n '%s' -p '/dataset' -d '%s'`
  29. SubTaskName = "task1"
  30. Success = "S000"
  31. DefaultBranchName = "master"
  32. ResultPath = "/result"
  33. )
  34. var (
  35. ResourceSpecs *models.ResourceSpecs
  36. TrainResourceSpecs *models.ResourceSpecs
  37. )
  38. type GenerateCloudBrainTaskReq struct {
  39. Ctx *context.Context
  40. DisplayJobName string
  41. JobName string
  42. Image string
  43. Command string
  44. CodePath string
  45. ModelPath string
  46. BenchmarkPath string
  47. Snn4ImageNetPath string
  48. BrainScorePath string
  49. JobType string
  50. GpuQueue string
  51. Description string
  52. BranchName string
  53. BootFile string
  54. Params string
  55. CommitID string
  56. Uuids string
  57. DatasetNames string
  58. DatasetInfos map[string]models.DatasetInfo
  59. BenchmarkTypeID int
  60. BenchmarkChildTypeID int
  61. ResourceSpecId int
  62. ResultPath string
  63. TrainUrl string
  64. ModelName string
  65. ModelVersion string
  66. CkptName string
  67. }
  68. func isAdminOrOwnerOrJobCreater(ctx *context.Context, job *models.Cloudbrain, err error) bool {
  69. if !ctx.IsSigned {
  70. return false
  71. }
  72. if err != nil {
  73. return ctx.IsUserRepoOwner() || ctx.IsUserSiteAdmin()
  74. } else {
  75. return ctx.IsUserRepoOwner() || ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
  76. }
  77. }
  78. func CanDeleteJob(ctx *context.Context, job *models.Cloudbrain) bool {
  79. return isAdminOrOwnerOrJobCreater(ctx, job, nil)
  80. }
  81. func CanCreateOrDebugJob(ctx *context.Context) bool {
  82. if !ctx.IsSigned {
  83. return false
  84. }
  85. return ctx.Repo.CanWrite(models.UnitTypeCloudBrain)
  86. }
  87. func CanModifyJob(ctx *context.Context, job *models.Cloudbrain) bool {
  88. return isAdminOrJobCreater(ctx, job, nil)
  89. }
  90. func isAdminOrJobCreater(ctx *context.Context, job *models.Cloudbrain, err error) bool {
  91. if !ctx.IsSigned {
  92. return false
  93. }
  94. if err != nil {
  95. return ctx.IsUserSiteAdmin()
  96. } else {
  97. return ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
  98. }
  99. }
  100. func isAdminOrImageCreater(ctx *context.Context, image *models.Image, err error) bool {
  101. if !ctx.IsSigned {
  102. return false
  103. }
  104. if err != nil {
  105. return ctx.IsUserSiteAdmin()
  106. } else {
  107. return ctx.IsUserSiteAdmin() || ctx.User.ID == image.UID
  108. }
  109. }
  110. func AdminOrOwnerOrJobCreaterRight(ctx *context.Context) {
  111. var ID = ctx.Params(":id")
  112. job, err := models.GetCloudbrainByID(ID)
  113. if err != nil {
  114. log.Error("GetCloudbrainByID failed:%v", err.Error())
  115. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  116. }
  117. ctx.Cloudbrain = job
  118. if !isAdminOrOwnerOrJobCreater(ctx, job, err) {
  119. log.Error("!isAdminOrOwnerOrJobCreater error:%v", err.Error())
  120. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  121. }
  122. }
  123. func AdminOrJobCreaterRight(ctx *context.Context) {
  124. var ID = ctx.Params(":id")
  125. job, err := models.GetCloudbrainByID(ID)
  126. if err != nil {
  127. log.Error("GetCloudbrainByID failed:%v", err.Error())
  128. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  129. }
  130. ctx.Cloudbrain = job
  131. if !isAdminOrJobCreater(ctx, job, err) {
  132. log.Error("!isAdminOrJobCreater error:%v", err.Error())
  133. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  134. }
  135. }
  136. func AdminOrOwnerOrJobCreaterRightForTrain(ctx *context.Context) {
  137. var jobID = ctx.Params(":jobid")
  138. job, err := models.GetCloudbrainByJobID(jobID)
  139. if err != nil {
  140. log.Error("GetCloudbrainByJobID failed:%v", err.Error())
  141. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  142. }
  143. ctx.Cloudbrain = job
  144. if !isAdminOrOwnerOrJobCreater(ctx, job, err) {
  145. log.Error("!isAdminOrOwnerOrJobCreater failed:%v", err.Error())
  146. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  147. }
  148. }
  149. func AdminOrJobCreaterRightForTrain(ctx *context.Context) {
  150. var jobID = ctx.Params(":jobid")
  151. job, err := models.GetCloudbrainByJobID(jobID)
  152. if err != nil {
  153. log.Error("GetCloudbrainByJobID failed:%v", err.Error())
  154. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  155. }
  156. ctx.Cloudbrain = job
  157. if !isAdminOrJobCreater(ctx, job, err) {
  158. log.Error("!isAdminOrJobCreater errot:%v", err.Error())
  159. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  160. }
  161. }
  162. func AdminOrImageCreaterRight(ctx *context.Context) {
  163. id, err := strconv.ParseInt(ctx.Params(":id"), 10, 64)
  164. var image *models.Image
  165. if err != nil {
  166. log.Error("Get Image by ID failed:%v", err.Error())
  167. } else {
  168. image, err = models.GetImageByID(id)
  169. if err != nil {
  170. log.Error("Get Image by ID failed:%v", err.Error())
  171. return
  172. }
  173. }
  174. if !isAdminOrImageCreater(ctx, image, err) {
  175. log.Error("!isAdminOrImageCreater error:%v", err.Error())
  176. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  177. }
  178. }
  179. func GenerateTask(req GenerateCloudBrainTaskReq) error {
  180. var resourceSpec *models.ResourceSpec
  181. var versionCount int
  182. if req.JobType == string(models.JobTypeTrain) || req.JobType == string(models.JobTypeInference) {
  183. versionCount = 1
  184. if TrainResourceSpecs == nil {
  185. json.Unmarshal([]byte(setting.TrainResourceSpecs), &TrainResourceSpecs)
  186. }
  187. for _, spec := range TrainResourceSpecs.ResourceSpec {
  188. if req.ResourceSpecId == spec.Id {
  189. resourceSpec = spec
  190. }
  191. }
  192. } else {
  193. if ResourceSpecs == nil {
  194. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  195. }
  196. for _, spec := range ResourceSpecs.ResourceSpec {
  197. if req.ResourceSpecId == spec.Id {
  198. resourceSpec = spec
  199. }
  200. }
  201. }
  202. if resourceSpec == nil {
  203. log.Error("no such resourceSpecId(%d)", req.ResourceSpecId, req.Ctx.Data["MsgID"])
  204. return errors.New("no such resourceSpec")
  205. }
  206. volumes := []models.Volume{
  207. {
  208. HostPath: models.StHostPath{
  209. Path: req.CodePath,
  210. MountPath: CodeMountPath,
  211. ReadOnly: false,
  212. },
  213. },
  214. {
  215. HostPath: models.StHostPath{
  216. Path: req.ModelPath,
  217. MountPath: ModelMountPath,
  218. ReadOnly: false,
  219. },
  220. },
  221. {
  222. HostPath: models.StHostPath{
  223. Path: req.BenchmarkPath,
  224. MountPath: BenchMarkMountPath,
  225. ReadOnly: true,
  226. },
  227. },
  228. {
  229. HostPath: models.StHostPath{
  230. Path: req.Snn4ImageNetPath,
  231. MountPath: Snn4imagenetMountPath,
  232. ReadOnly: true,
  233. },
  234. },
  235. {
  236. HostPath: models.StHostPath{
  237. Path: req.BrainScorePath,
  238. MountPath: BrainScoreMountPath,
  239. ReadOnly: true,
  240. },
  241. },
  242. {
  243. HostPath: models.StHostPath{
  244. Path: req.ResultPath,
  245. MountPath: ResultPath,
  246. ReadOnly: true,
  247. },
  248. },
  249. }
  250. if len(req.DatasetInfos) == 1 {
  251. volumes = append(volumes, models.Volume{
  252. HostPath: models.StHostPath{
  253. Path: req.DatasetInfos[req.Uuids].DataLocalPath,
  254. MountPath: DataSetMountPath,
  255. ReadOnly: true,
  256. },
  257. })
  258. } else {
  259. for _, dataset := range req.DatasetInfos {
  260. volumes = append(volumes, models.Volume{
  261. HostPath: models.StHostPath{
  262. Path: dataset.DataLocalPath,
  263. MountPath: DataSetMountPath + "/" + dataset.Name,
  264. ReadOnly: true,
  265. },
  266. })
  267. }
  268. }
  269. createTime := timeutil.TimeStampNow()
  270. jobResult, err := CreateJob(req.JobName, models.CreateJobParams{
  271. JobName: req.JobName,
  272. RetryCount: 1,
  273. GpuType: req.GpuQueue,
  274. Image: req.Image,
  275. TaskRoles: []models.TaskRole{
  276. {
  277. Name: SubTaskName,
  278. TaskNumber: 1,
  279. MinSucceededTaskCount: 1,
  280. MinFailedTaskCount: 1,
  281. CPUNumber: resourceSpec.CpuNum,
  282. GPUNumber: resourceSpec.GpuNum,
  283. MemoryMB: resourceSpec.MemMiB,
  284. ShmMB: resourceSpec.ShareMemMiB,
  285. Command: req.Command,
  286. NeedIBDevice: false,
  287. IsMainRole: false,
  288. UseNNI: false,
  289. },
  290. },
  291. Volumes: volumes,
  292. })
  293. if err != nil {
  294. log.Error("CreateJob failed:", err.Error(), req.Ctx.Data["MsgID"])
  295. return err
  296. }
  297. if jobResult.Code != Success {
  298. log.Error("CreateJob(%s) failed:%s", req.JobName, jobResult.Msg, req.Ctx.Data["MsgID"])
  299. return errors.New(jobResult.Msg)
  300. }
  301. var jobID = jobResult.Payload["jobId"].(string)
  302. err = models.CreateCloudbrain(&models.Cloudbrain{
  303. Status: string(models.JobWaiting),
  304. UserID: req.Ctx.User.ID,
  305. RepoID: req.Ctx.Repo.Repository.ID,
  306. JobID: jobID,
  307. JobName: req.JobName,
  308. DisplayJobName: req.DisplayJobName,
  309. SubTaskName: SubTaskName,
  310. JobType: req.JobType,
  311. Type: models.TypeCloudBrainOne,
  312. Uuid: req.Uuids,
  313. Image: req.Image,
  314. GpuQueue: req.GpuQueue,
  315. ResourceSpecId: req.ResourceSpecId,
  316. ComputeResource: models.GPUResource,
  317. BenchmarkTypeID: req.BenchmarkTypeID,
  318. BenchmarkChildTypeID: req.BenchmarkChildTypeID,
  319. Description: req.Description,
  320. IsLatestVersion: "1",
  321. VersionCount: versionCount,
  322. BranchName: req.BranchName,
  323. BootFile: req.BootFile,
  324. DatasetName: req.DatasetNames,
  325. Parameters: req.Params,
  326. TrainUrl: req.TrainUrl,
  327. ModelName: req.ModelName,
  328. ModelVersion: req.ModelVersion,
  329. CkptName: req.CkptName,
  330. ResultUrl: req.ResultPath,
  331. CreatedUnix: createTime,
  332. UpdatedUnix: createTime,
  333. CommitID: req.CommitID,
  334. })
  335. if err != nil {
  336. return err
  337. }
  338. task, err := models.GetCloudbrainByJobID(jobID)
  339. if err != nil {
  340. log.Error("GetCloudbrainByJobID failed: %v", err.Error())
  341. return err
  342. }
  343. stringId := strconv.FormatInt(task.ID, 10)
  344. if IsBenchmarkJob(req.JobType) {
  345. notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, stringId, req.DisplayJobName, models.ActionCreateBenchMarkTask)
  346. } else if string(models.JobTypeTrain) == req.JobType {
  347. notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, jobID, req.DisplayJobName, models.ActionCreateGPUTrainTask)
  348. } else if string(models.JobTypeInference) == req.JobType {
  349. notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, jobID, req.DisplayJobName, models.ActionCreateInferenceTask)
  350. } else {
  351. notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, stringId, req.DisplayJobName, models.ActionCreateDebugGPUTask)
  352. }
  353. return nil
  354. }
  355. func IsBenchmarkJob(jobType string) bool {
  356. return string(models.JobTypeBenchmark) == jobType || string(models.JobTypeBrainScore) == jobType || string(models.JobTypeSnn4imagenet) == jobType
  357. }
  358. func GetWaitingCloudbrainCount(cloudbrainType int, computeResource string, jobTypes ...models.JobType) int64 {
  359. num, err := models.GetWaitingCloudbrainCount(cloudbrainType, computeResource, jobTypes...)
  360. if err != nil {
  361. log.Warn("Get waiting count err", err)
  362. num = 0
  363. }
  364. return num
  365. }
  366. func RestartTask(ctx *context.Context, task *models.Cloudbrain, newID *string) error {
  367. jobName := task.JobName
  368. var resourceSpec *models.ResourceSpec
  369. if ResourceSpecs == nil {
  370. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  371. }
  372. for _, spec := range ResourceSpecs.ResourceSpec {
  373. if task.ResourceSpecId == spec.Id {
  374. resourceSpec = spec
  375. }
  376. }
  377. if resourceSpec == nil {
  378. log.Error("no such resourceSpecId(%d)", task.ResourceSpecId, ctx.Data["MsgID"])
  379. return errors.New("no such resourceSpec")
  380. }
  381. datasetInfos, _, err := models.GetDatasetInfo(task.Uuid)
  382. if err != nil {
  383. log.Error("GetDatasetInfo failed:%v", err, ctx.Data["MsgID"])
  384. return err
  385. }
  386. volumes := []models.Volume{
  387. {
  388. HostPath: models.StHostPath{
  389. Path: storage.GetMinioPath(jobName, CodeMountPath+"/"),
  390. MountPath: CodeMountPath,
  391. ReadOnly: false,
  392. },
  393. },
  394. {
  395. HostPath: models.StHostPath{
  396. Path: storage.GetMinioPath(jobName, ModelMountPath+"/"),
  397. MountPath: ModelMountPath,
  398. ReadOnly: false,
  399. },
  400. },
  401. {
  402. HostPath: models.StHostPath{
  403. Path: storage.GetMinioPath(jobName, BenchMarkMountPath+"/"),
  404. MountPath: BenchMarkMountPath,
  405. ReadOnly: true,
  406. },
  407. },
  408. {
  409. HostPath: models.StHostPath{
  410. Path: storage.GetMinioPath(jobName, Snn4imagenetMountPath+"/"),
  411. MountPath: Snn4imagenetMountPath,
  412. ReadOnly: true,
  413. },
  414. },
  415. {
  416. HostPath: models.StHostPath{
  417. Path: storage.GetMinioPath(jobName, BrainScoreMountPath+"/"),
  418. MountPath: BrainScoreMountPath,
  419. ReadOnly: true,
  420. },
  421. },
  422. }
  423. if len(datasetInfos) == 1 {
  424. volumes = append(volumes, models.Volume{
  425. HostPath: models.StHostPath{
  426. Path: datasetInfos[task.Uuid].DataLocalPath,
  427. MountPath: DataSetMountPath,
  428. ReadOnly: true,
  429. },
  430. })
  431. } else {
  432. for _, dataset := range datasetInfos {
  433. volumes = append(volumes, models.Volume{
  434. HostPath: models.StHostPath{
  435. Path: dataset.DataLocalPath,
  436. MountPath: DataSetMountPath + "/" + dataset.Name,
  437. ReadOnly: true,
  438. },
  439. })
  440. }
  441. }
  442. createTime := timeutil.TimeStampNow()
  443. jobResult, err := CreateJob(jobName, models.CreateJobParams{
  444. JobName: jobName,
  445. RetryCount: 1,
  446. GpuType: task.GpuQueue,
  447. Image: task.Image,
  448. TaskRoles: []models.TaskRole{
  449. {
  450. Name: SubTaskName,
  451. TaskNumber: 1,
  452. MinSucceededTaskCount: 1,
  453. MinFailedTaskCount: 1,
  454. CPUNumber: resourceSpec.CpuNum,
  455. GPUNumber: resourceSpec.GpuNum,
  456. MemoryMB: resourceSpec.MemMiB,
  457. ShmMB: resourceSpec.ShareMemMiB,
  458. Command: Command,
  459. NeedIBDevice: false,
  460. IsMainRole: false,
  461. UseNNI: false,
  462. },
  463. },
  464. Volumes: volumes,
  465. })
  466. if err != nil {
  467. log.Error("CreateJob failed:%v", err.Error(), ctx.Data["MsgID"])
  468. return err
  469. }
  470. if jobResult.Code != Success {
  471. log.Error("CreateJob(%s) failed:%s", jobName, jobResult.Msg, ctx.Data["MsgID"])
  472. return errors.New(jobResult.Msg)
  473. }
  474. var jobID = jobResult.Payload["jobId"].(string)
  475. newTask := &models.Cloudbrain{
  476. Status: string(models.JobWaiting),
  477. UserID: task.UserID,
  478. RepoID: task.RepoID,
  479. JobID: jobID,
  480. JobName: task.JobName,
  481. DisplayJobName: task.DisplayJobName,
  482. SubTaskName: task.SubTaskName,
  483. JobType: task.JobType,
  484. Type: task.Type,
  485. Uuid: task.Uuid,
  486. DatasetName: task.DatasetName,
  487. Image: task.Image,
  488. GpuQueue: task.GpuQueue,
  489. ResourceSpecId: task.ResourceSpecId,
  490. ComputeResource: task.ComputeResource,
  491. CreatedUnix: createTime,
  492. UpdatedUnix: createTime,
  493. BranchName: task.BranchName,
  494. }
  495. err = models.RestartCloudbrain(task, newTask)
  496. if err != nil {
  497. log.Error("RestartCloudbrain(%s) failed:%v", jobName, err.Error(), ctx.Data["MsgID"])
  498. return err
  499. }
  500. stringId := strconv.FormatInt(newTask.ID, 10)
  501. *newID = stringId
  502. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, task.DisplayJobName, models.ActionCreateDebugGPUTask)
  503. return nil
  504. }