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

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