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