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

4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package cloudbrain
  2. import (
  3. "code.gitea.io/gitea/modules/timeutil"
  4. "encoding/json"
  5. "errors"
  6. "strconv"
  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 = Command + ";" + `/opt/conda/bin/python /snn4imagenet/testSNN_script.py --modelname '%s' --modelpath '/dataset' --modeldescription '%s'`
  28. BrainScoreCommand = Command + ";" + `/opt/conda/bin/python /brainscore/score_a_model.py --brainRegion '%s' --modelname '%s' --modelpath '/dataset' --modeldescription '%s'` + ";"
  29. SubTaskName = "task1"
  30. Success = "S000"
  31. DefaultBranchName = "master"
  32. )
  33. var (
  34. ResourceSpecs *models.ResourceSpecs
  35. TrainResourceSpecs *models.ResourceSpecs
  36. )
  37. func isAdminOrOwnerOrJobCreater(ctx *context.Context, job *models.Cloudbrain, err error) bool {
  38. if !ctx.IsSigned {
  39. return false
  40. }
  41. log.Info("is repo owner:" + strconv.FormatBool(ctx.IsUserRepoOwner()))
  42. log.Info("is user admin:" + strconv.FormatBool(ctx.IsUserSiteAdmin()))
  43. if err != nil {
  44. return ctx.IsUserRepoOwner() || ctx.IsUserSiteAdmin()
  45. } else {
  46. log.Info("is job creator:" + strconv.FormatBool(ctx.User.ID == job.UserID))
  47. return ctx.IsUserRepoOwner() || ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
  48. }
  49. }
  50. func CanDeleteJob(ctx *context.Context, job *models.Cloudbrain) bool {
  51. return isAdminOrOwnerOrJobCreater(ctx, job, nil)
  52. }
  53. func CanCreateOrDebugJob(ctx *context.Context) bool {
  54. if !ctx.IsSigned {
  55. return false
  56. }
  57. return ctx.Repo.CanWrite(models.UnitTypeCloudBrain)
  58. }
  59. func CanModifyJob(ctx *context.Context, job *models.Cloudbrain) bool {
  60. return isAdminOrJobCreater(ctx, job, nil)
  61. }
  62. func isAdminOrJobCreater(ctx *context.Context, job *models.Cloudbrain, err error) bool {
  63. if !ctx.IsSigned {
  64. return false
  65. }
  66. if err != nil {
  67. return ctx.IsUserSiteAdmin()
  68. } else {
  69. return ctx.IsUserSiteAdmin() || ctx.User.ID == job.UserID
  70. }
  71. }
  72. func isAdminOrImageCreater(ctx *context.Context, image *models.Image, err error) bool {
  73. if !ctx.IsSigned {
  74. return false
  75. }
  76. if err != nil {
  77. return ctx.IsUserSiteAdmin()
  78. } else {
  79. return ctx.IsUserSiteAdmin() || ctx.User.ID == image.UID
  80. }
  81. }
  82. func AdminOrOwnerOrJobCreaterRight(ctx *context.Context) {
  83. var ID = ctx.Params(":id")
  84. job, err := models.GetCloudbrainByID(ID)
  85. if err != nil {
  86. log.Error("GetCloudbrainByID failed:%v", err.Error())
  87. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  88. }
  89. ctx.Cloudbrain = job
  90. if !isAdminOrOwnerOrJobCreater(ctx, job, err) {
  91. log.Error("!isAdminOrOwnerOrJobCreater error:%v", err.Error())
  92. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  93. }
  94. }
  95. func AdminOrJobCreaterRight(ctx *context.Context) {
  96. var ID = ctx.Params(":id")
  97. job, err := models.GetCloudbrainByID(ID)
  98. if err != nil {
  99. log.Error("GetCloudbrainByID failed:%v", err.Error())
  100. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  101. }
  102. ctx.Cloudbrain = job
  103. if !isAdminOrJobCreater(ctx, job, err) {
  104. log.Error("!isAdminOrJobCreater error:%v", err.Error())
  105. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  106. }
  107. }
  108. func AdminOrOwnerOrJobCreaterRightForTrain(ctx *context.Context) {
  109. var jobID = ctx.Params(":jobid")
  110. job, err := models.GetCloudbrainByJobID(jobID)
  111. if err != nil {
  112. log.Error("GetCloudbrainByJobID failed:%v", err.Error())
  113. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  114. }
  115. ctx.Cloudbrain = job
  116. if !isAdminOrOwnerOrJobCreater(ctx, job, err) {
  117. log.Error("!isAdminOrOwnerOrJobCreater failed:%v", err.Error())
  118. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  119. }
  120. }
  121. func AdminOrJobCreaterRightForTrain(ctx *context.Context) {
  122. var jobID = ctx.Params(":jobid")
  123. job, err := models.GetCloudbrainByJobID(jobID)
  124. if err != nil {
  125. log.Error("GetCloudbrainByJobID failed:%v", err.Error())
  126. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  127. }
  128. ctx.Cloudbrain = job
  129. if !isAdminOrJobCreater(ctx, job, err) {
  130. log.Error("!isAdminOrJobCreater errot:%v", err.Error())
  131. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  132. }
  133. }
  134. func AdminOrImageCreaterRight(ctx *context.Context) {
  135. id, err := strconv.ParseInt(ctx.Params(":id"), 10, 64)
  136. var image *models.Image
  137. if err != nil {
  138. log.Error("Get Image by ID failed:%v", err.Error())
  139. } else {
  140. image, err = models.GetImageByID(id)
  141. if err != nil {
  142. log.Error("Get Image by ID failed:%v", err.Error())
  143. return
  144. }
  145. }
  146. if !isAdminOrImageCreater(ctx, image, err) {
  147. log.Error("!isAdminOrImageCreater error:%v", err.Error())
  148. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  149. }
  150. }
  151. func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, brainScorePath, jobType, gpuQueue, description, branchName, bootFile, params string, benchmarkTypeID, benchmarkChildTypeID, resourceSpecId int) error {
  152. dataActualPath := setting.Attachment.Minio.RealPath +
  153. setting.Attachment.Minio.Bucket + "/" +
  154. setting.Attachment.Minio.BasePath +
  155. models.AttachmentRelativePath(uuid) +
  156. uuid
  157. var resourceSpec *models.ResourceSpec
  158. var versionCount int
  159. if jobType == string(models.JobTypeTrain) {
  160. versionCount = 1
  161. if TrainResourceSpecs == nil {
  162. json.Unmarshal([]byte(setting.TrainResourceSpecs), &TrainResourceSpecs)
  163. }
  164. for _, spec := range TrainResourceSpecs.ResourceSpec {
  165. if resourceSpecId == spec.Id {
  166. resourceSpec = spec
  167. }
  168. }
  169. } else {
  170. if ResourceSpecs == nil {
  171. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  172. }
  173. for _, spec := range ResourceSpecs.ResourceSpec {
  174. if resourceSpecId == spec.Id {
  175. resourceSpec = spec
  176. }
  177. }
  178. }
  179. if resourceSpec == nil {
  180. log.Error("no such resourceSpecId(%d)", resourceSpecId, ctx.Data["MsgID"])
  181. return errors.New("no such resourceSpec")
  182. }
  183. var datasetName string
  184. attach, err := models.GetAttachmentByUUID(uuid)
  185. if err != nil {
  186. //for benchmark, do not return error
  187. log.Error("GetAttachmentByUUID failed:%v", err)
  188. } else {
  189. datasetName = attach.Name
  190. }
  191. createTime := timeutil.TimeStampNow()
  192. jobResult, err := CreateJob(jobName, models.CreateJobParams{
  193. JobName: jobName,
  194. RetryCount: 1,
  195. GpuType: gpuQueue,
  196. Image: image,
  197. TaskRoles: []models.TaskRole{
  198. {
  199. Name: SubTaskName,
  200. TaskNumber: 1,
  201. MinSucceededTaskCount: 1,
  202. MinFailedTaskCount: 1,
  203. CPUNumber: resourceSpec.CpuNum,
  204. GPUNumber: resourceSpec.GpuNum,
  205. MemoryMB: resourceSpec.MemMiB,
  206. ShmMB: resourceSpec.ShareMemMiB,
  207. Command: command,
  208. NeedIBDevice: false,
  209. IsMainRole: false,
  210. UseNNI: false,
  211. },
  212. },
  213. Volumes: []models.Volume{
  214. {
  215. HostPath: models.StHostPath{
  216. Path: codePath,
  217. MountPath: CodeMountPath,
  218. ReadOnly: false,
  219. },
  220. },
  221. {
  222. HostPath: models.StHostPath{
  223. Path: dataActualPath,
  224. MountPath: DataSetMountPath,
  225. ReadOnly: true,
  226. },
  227. },
  228. {
  229. HostPath: models.StHostPath{
  230. Path: modelPath,
  231. MountPath: ModelMountPath,
  232. ReadOnly: false,
  233. },
  234. },
  235. {
  236. HostPath: models.StHostPath{
  237. Path: benchmarkPath,
  238. MountPath: BenchMarkMountPath,
  239. ReadOnly: true,
  240. },
  241. },
  242. {
  243. HostPath: models.StHostPath{
  244. Path: snn4imagenetPath,
  245. MountPath: Snn4imagenetMountPath,
  246. ReadOnly: true,
  247. },
  248. },
  249. {
  250. HostPath: models.StHostPath{
  251. Path: brainScorePath,
  252. MountPath: BrainScoreMountPath,
  253. ReadOnly: true,
  254. },
  255. },
  256. },
  257. })
  258. if err != nil {
  259. log.Error("CreateJob failed:", err.Error(), ctx.Data["MsgID"])
  260. return err
  261. }
  262. if jobResult.Code != Success {
  263. log.Error("CreateJob(%s) failed:%s", jobName, jobResult.Msg, ctx.Data["MsgID"])
  264. return errors.New(jobResult.Msg)
  265. }
  266. var jobID = jobResult.Payload["jobId"].(string)
  267. err = models.CreateCloudbrain(&models.Cloudbrain{
  268. Status: string(models.JobWaiting),
  269. UserID: ctx.User.ID,
  270. RepoID: ctx.Repo.Repository.ID,
  271. JobID: jobID,
  272. JobName: jobName,
  273. DisplayJobName: displayJobName,
  274. SubTaskName: SubTaskName,
  275. JobType: jobType,
  276. Type: models.TypeCloudBrainOne,
  277. Uuid: uuid,
  278. Image: image,
  279. GpuQueue: gpuQueue,
  280. ResourceSpecId: resourceSpecId,
  281. ComputeResource: models.GPUResource,
  282. BenchmarkTypeID: benchmarkTypeID,
  283. BenchmarkChildTypeID: benchmarkChildTypeID,
  284. Description: description,
  285. IsLatestVersion: "1",
  286. VersionCount: versionCount,
  287. BranchName: branchName,
  288. BootFile: bootFile,
  289. DatasetName: datasetName,
  290. Parameters: params,
  291. CreatedUnix: createTime,
  292. UpdatedUnix: createTime,
  293. })
  294. if err != nil {
  295. return err
  296. }
  297. task, err := models.GetCloudbrainByJobID(jobID)
  298. if err != nil {
  299. log.Error("GetCloudbrainByName failed: %v", err.Error())
  300. return err
  301. }
  302. stringId := strconv.FormatInt(task.ID, 10)
  303. if string(models.JobTypeBenchmark) == jobType {
  304. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, displayJobName, models.ActionCreateBenchMarkTask)
  305. } else if string(models.JobTypeTrain) == jobType {
  306. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, jobID, displayJobName, models.ActionCreateGPUTrainTask)
  307. } else {
  308. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, displayJobName, models.ActionCreateDebugGPUTask)
  309. }
  310. return nil
  311. }
  312. func RestartTask(ctx *context.Context, task *models.Cloudbrain, newID *string) error {
  313. dataActualPath := setting.Attachment.Minio.RealPath +
  314. setting.Attachment.Minio.Bucket + "/" +
  315. setting.Attachment.Minio.BasePath +
  316. models.AttachmentRelativePath(task.Uuid) +
  317. task.Uuid
  318. jobName := task.JobName
  319. var resourceSpec *models.ResourceSpec
  320. if ResourceSpecs == nil {
  321. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  322. }
  323. for _, spec := range ResourceSpecs.ResourceSpec {
  324. if task.ResourceSpecId == spec.Id {
  325. resourceSpec = spec
  326. }
  327. }
  328. if resourceSpec == nil {
  329. log.Error("no such resourceSpecId(%d)", task.ResourceSpecId, ctx.Data["MsgID"])
  330. return errors.New("no such resourceSpec")
  331. }
  332. createTime := timeutil.TimeStampNow()
  333. jobResult, err := CreateJob(jobName, models.CreateJobParams{
  334. JobName: jobName,
  335. RetryCount: 1,
  336. GpuType: task.GpuQueue,
  337. Image: task.Image,
  338. TaskRoles: []models.TaskRole{
  339. {
  340. Name: SubTaskName,
  341. TaskNumber: 1,
  342. MinSucceededTaskCount: 1,
  343. MinFailedTaskCount: 1,
  344. CPUNumber: resourceSpec.CpuNum,
  345. GPUNumber: resourceSpec.GpuNum,
  346. MemoryMB: resourceSpec.MemMiB,
  347. ShmMB: resourceSpec.ShareMemMiB,
  348. Command: Command,
  349. NeedIBDevice: false,
  350. IsMainRole: false,
  351. UseNNI: false,
  352. },
  353. },
  354. Volumes: []models.Volume{
  355. {
  356. HostPath: models.StHostPath{
  357. Path: storage.GetMinioPath(jobName, CodeMountPath+"/"),
  358. MountPath: CodeMountPath,
  359. ReadOnly: false,
  360. },
  361. },
  362. {
  363. HostPath: models.StHostPath{
  364. Path: dataActualPath,
  365. MountPath: DataSetMountPath,
  366. ReadOnly: true,
  367. },
  368. },
  369. {
  370. HostPath: models.StHostPath{
  371. Path: storage.GetMinioPath(jobName, ModelMountPath+"/"),
  372. MountPath: ModelMountPath,
  373. ReadOnly: false,
  374. },
  375. },
  376. {
  377. HostPath: models.StHostPath{
  378. Path: storage.GetMinioPath(jobName, BenchMarkMountPath+"/"),
  379. MountPath: BenchMarkMountPath,
  380. ReadOnly: true,
  381. },
  382. },
  383. {
  384. HostPath: models.StHostPath{
  385. Path: storage.GetMinioPath(jobName, Snn4imagenetMountPath+"/"),
  386. MountPath: Snn4imagenetMountPath,
  387. ReadOnly: true,
  388. },
  389. },
  390. {
  391. HostPath: models.StHostPath{
  392. Path: storage.GetMinioPath(jobName, BrainScoreMountPath+"/"),
  393. MountPath: BrainScoreMountPath,
  394. ReadOnly: true,
  395. },
  396. },
  397. },
  398. })
  399. if err != nil {
  400. log.Error("CreateJob failed:%v", err.Error(), ctx.Data["MsgID"])
  401. return err
  402. }
  403. if jobResult.Code != Success {
  404. log.Error("CreateJob(%s) failed:%s", jobName, jobResult.Msg, ctx.Data["MsgID"])
  405. return errors.New(jobResult.Msg)
  406. }
  407. var jobID = jobResult.Payload["jobId"].(string)
  408. newTask := &models.Cloudbrain{
  409. Status: string(models.JobWaiting),
  410. UserID: task.UserID,
  411. RepoID: task.RepoID,
  412. JobID: jobID,
  413. JobName: task.JobName,
  414. DisplayJobName: task.DisplayJobName,
  415. SubTaskName: task.SubTaskName,
  416. JobType: task.JobType,
  417. Type: task.Type,
  418. Uuid: task.Uuid,
  419. Image: task.Image,
  420. GpuQueue: task.GpuQueue,
  421. ResourceSpecId: task.ResourceSpecId,
  422. ComputeResource: task.ComputeResource,
  423. CreatedUnix: createTime,
  424. UpdatedUnix: createTime,
  425. BranchName: task.BranchName,
  426. }
  427. err = models.RestartCloudbrain(task, newTask)
  428. if err != nil {
  429. log.Error("RestartCloudbrain(%s) failed:%v", jobName, err.Error(), ctx.Data["MsgID"])
  430. return err
  431. }
  432. stringId := strconv.FormatInt(newTask.ID, 10)
  433. *newID = stringId
  434. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, task.DisplayJobName, models.ActionCreateDebugGPUTask)
  435. return nil
  436. }