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

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
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 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
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
4 years ago
4 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
4 years ago
3 years ago
4 years ago
5 years ago
5 years ago
5 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 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
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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/storage"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/auth"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/cloudbrain"
  20. "code.gitea.io/gitea/modules/context"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. const (
  25. tplCloudBrainIndex base.TplName = "repo/cloudbrain/index"
  26. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  27. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  28. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  29. )
  30. var (
  31. gpuInfos *models.GpuInfos
  32. categories *models.Categories
  33. )
  34. // MustEnableDataset check if repository enable internal cb
  35. func MustEnableCloudbrain(ctx *context.Context) {
  36. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  37. ctx.NotFound("MustEnableCloudbrain", nil)
  38. return
  39. }
  40. }
  41. func CloudBrainIndex(ctx *context.Context) {
  42. MustEnableCloudbrain(ctx)
  43. repo := ctx.Repo.Repository
  44. page := ctx.QueryInt("page")
  45. if page <= 0 {
  46. page = 1
  47. }
  48. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  49. ListOptions: models.ListOptions{
  50. Page: page,
  51. PageSize: setting.UI.IssuePagingNum,
  52. },
  53. RepoID: repo.ID,
  54. Type: models.TypeCloudBrainOne,
  55. })
  56. if err != nil {
  57. ctx.ServerError("Cloudbrain", err)
  58. return
  59. }
  60. timestamp := time.Now().Unix()
  61. for i, task := range ciTasks {
  62. if task.Status == string(models.JobRunning) && (timestamp-int64(task.CreatedUnix) > 30) {
  63. ciTasks[i].CanDebug = true
  64. } else {
  65. ciTasks[i].CanDebug = false
  66. }
  67. }
  68. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  69. pager.SetDefaultParams(ctx)
  70. ctx.Data["Page"] = pager
  71. ctx.Data["PageIsCloudBrain"] = true
  72. ctx.Data["Tasks"] = ciTasks
  73. ctx.HTML(200, tplCloudBrainIndex)
  74. }
  75. func cutString(str string, lens int) string {
  76. if len(str) < lens {
  77. return str
  78. }
  79. return str[:lens]
  80. }
  81. func jobNamePrefixValid(s string) string {
  82. lowStr := strings.ToLower(s)
  83. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  84. removeSpecial := re.ReplaceAllString(lowStr, "")
  85. re = regexp.MustCompile(`^[_\\-]+`)
  86. return re.ReplaceAllString(removeSpecial, "")
  87. }
  88. func cloudBrainNewDataPrepare(ctx *context.Context) error{
  89. ctx.Data["PageIsCloudBrain"] = true
  90. t := time.Now()
  91. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  92. ctx.Data["job_name"] = jobName
  93. result, err := cloudbrain.GetImages()
  94. if err != nil {
  95. ctx.Data["error"] = err.Error()
  96. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  97. }
  98. for i, payload := range result.Payload.ImageInfo {
  99. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  100. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  101. } else {
  102. result.Payload.ImageInfo[i].PlaceView = payload.Place
  103. }
  104. }
  105. ctx.Data["images"] = result.Payload.ImageInfo
  106. resultPublic, err := cloudbrain.GetPublicImages()
  107. if err != nil {
  108. ctx.Data["error"] = err.Error()
  109. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  110. }
  111. for i, payload := range resultPublic.Payload.ImageInfo {
  112. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  113. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  114. } else {
  115. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  116. }
  117. }
  118. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  119. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  120. if err != nil {
  121. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  122. return err
  123. }
  124. ctx.Data["attachments"] = attachs
  125. ctx.Data["command"] = cloudbrain.Command
  126. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  127. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  128. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  129. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  130. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  131. if categories == nil {
  132. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  133. }
  134. ctx.Data["benchmark_categories"] = categories.Category
  135. if gpuInfos == nil {
  136. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  137. }
  138. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  139. if cloudbrain.ResourceSpecs == nil {
  140. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  141. }
  142. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  143. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  144. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  145. return nil
  146. }
  147. func CloudBrainNew(ctx *context.Context) {
  148. err := cloudBrainNewDataPrepare(ctx)
  149. if err != nil {
  150. ctx.ServerError("get new cloudbrain info failed", err)
  151. return
  152. }
  153. ctx.HTML(200, tplCloudBrainNew)
  154. }
  155. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  156. ctx.Data["PageIsCloudBrain"] = true
  157. jobName := form.JobName
  158. image := form.Image
  159. command := form.Command
  160. uuid := form.Attachment
  161. jobType := form.JobType
  162. gpuQueue := setting.JobType
  163. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  164. resourceSpecId := form.ResourceSpecId
  165. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) {
  166. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  167. cloudBrainNewDataPrepare(ctx)
  168. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  169. return
  170. }
  171. _, err := models.GetCloudbrainByName(jobName)
  172. if err == nil {
  173. log.Error("the job name did already exist", ctx.Data["MsgID"])
  174. cloudBrainNewDataPrepare(ctx)
  175. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  176. return
  177. } else {
  178. if !models.IsErrJobNotExist(err) {
  179. log.Error("system error, %v", err, ctx.Data["MsgID"])
  180. cloudBrainNewDataPrepare(ctx)
  181. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  182. return
  183. }
  184. }
  185. repo := ctx.Repo.Repository
  186. downloadCode(repo, codePath)
  187. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  188. err = os.MkdirAll(modelPath, os.ModePerm)
  189. if err != nil {
  190. cloudBrainNewDataPrepare(ctx)
  191. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  192. return
  193. }
  194. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  195. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  196. gpuQueue = form.GpuType
  197. var gpuType string
  198. for _, gpuInfo := range gpuInfos.GpuInfo {
  199. if gpuInfo.Queue == gpuQueue {
  200. gpuType = gpuInfo.Value
  201. }
  202. }
  203. downloadRateCode(repo, jobName, setting.BenchmarkCode, benchmarkPath, form.BenchmarkCategory, gpuType)
  204. }
  205. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  206. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  207. downloadRateCode(repo, jobName, setting.Snn4imagenetCode, snn4imagenetPath, "", "")
  208. }
  209. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, jobType, gpuQueue, resourceSpecId)
  210. if err != nil {
  211. cloudBrainNewDataPrepare(ctx)
  212. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  213. return
  214. }
  215. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  216. }
  217. func CloudBrainShow(ctx *context.Context) {
  218. ctx.Data["PageIsCloudBrain"] = true
  219. var jobID = ctx.Params(":jobid")
  220. task, err := models.GetCloudbrainByJobID(jobID)
  221. if err != nil {
  222. ctx.Data["error"] = err.Error()
  223. }
  224. result, err := cloudbrain.GetJob(jobID)
  225. if err != nil {
  226. ctx.Data["error"] = err.Error()
  227. }
  228. if result != nil {
  229. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  230. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  231. ctx.Data["result"] = jobRes
  232. taskRoles := jobRes.TaskRoles
  233. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  234. ctx.Data["taskRes"] = taskRes
  235. task.Status = taskRes.TaskStatuses[0].State
  236. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  237. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  238. err = models.UpdateJob(task)
  239. if err != nil {
  240. ctx.Data["error"] = err.Error()
  241. }
  242. }
  243. ctx.Data["task"] = task
  244. ctx.Data["jobID"] = jobID
  245. ctx.HTML(200, tplCloudBrainShow)
  246. }
  247. func CloudBrainDebug(ctx *context.Context) {
  248. var jobID = ctx.Params(":jobid")
  249. task, err := models.GetCloudbrainByJobID(jobID)
  250. if err != nil {
  251. ctx.ServerError("GetCloudbrainByJobID failed", err)
  252. return
  253. }
  254. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  255. ctx.Redirect(debugUrl)
  256. }
  257. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  258. var jobID = ctx.Params(":jobid")
  259. task, err := models.GetCloudbrainByJobID(jobID)
  260. if err != nil {
  261. ctx.JSON(200, map[string]string{
  262. "result_code": "-1",
  263. "error_msg": "GetCloudbrainByJobID failed",
  264. })
  265. return
  266. }
  267. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  268. Ip: task.ContainerIp,
  269. TaskContainerId: task.ContainerID,
  270. ImageDescription: form.Description,
  271. ImageTag: form.Tag,
  272. })
  273. if err != nil {
  274. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  275. ctx.JSON(200, map[string]string{
  276. "result_code": "-1",
  277. "error_msg": "CommitImage failed",
  278. })
  279. return
  280. }
  281. ctx.JSON(200, map[string]string{
  282. "result_code": "0",
  283. "error_msg": "",
  284. })
  285. }
  286. func CloudBrainStop(ctx *context.Context) {
  287. var jobID = ctx.Params(":jobid")
  288. task, err := models.GetCloudbrainByJobID(jobID)
  289. if err != nil {
  290. ctx.ServerError("GetCloudbrainByJobID failed", err)
  291. return
  292. }
  293. if task.Status == string(models.JobStopped) {
  294. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  295. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  296. return
  297. }
  298. err = cloudbrain.StopJob(jobID)
  299. if err != nil {
  300. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  301. ctx.ServerError("StopJob failed", err)
  302. return
  303. }
  304. task.Status = string(models.JobStopped)
  305. err = models.UpdateJob(task)
  306. if err != nil {
  307. ctx.ServerError("UpdateJob failed", err)
  308. return
  309. }
  310. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  311. }
  312. func CloudBrainDel(ctx *context.Context) {
  313. var jobID = ctx.Params(":jobid")
  314. task, err := models.GetCloudbrainByJobID(jobID)
  315. if err != nil {
  316. ctx.ServerError("GetCloudbrainByJobID failed", err)
  317. return
  318. }
  319. if task.Status != string(models.JobStopped) {
  320. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  321. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  322. return
  323. }
  324. err = models.DeleteJob(task)
  325. if err != nil {
  326. ctx.ServerError("DeleteJob failed", err)
  327. return
  328. }
  329. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  330. }
  331. func CloudBrainShowModels(ctx *context.Context) {
  332. ctx.Data["PageIsCloudBrain"] = true
  333. jobID := ctx.Params(":jobid")
  334. parentDir := ctx.Query("parentDir")
  335. dirArray := strings.Split(parentDir, "/")
  336. task, err := models.GetCloudbrainByJobID(jobID)
  337. if err != nil {
  338. log.Error("no such job!", ctx.Data["msgID"])
  339. ctx.ServerError("no such job:", err)
  340. return
  341. }
  342. //get dirs
  343. dirs, err := getModelDirs(task.JobName, parentDir)
  344. if err != nil {
  345. log.Error("getModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  346. ctx.ServerError("getModelDirs failed:", err)
  347. return
  348. }
  349. var fileInfos []FileInfo
  350. err = json.Unmarshal([]byte(dirs), &fileInfos)
  351. if err != nil {
  352. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  353. ctx.ServerError("json.Unmarshal failed:", err)
  354. return
  355. }
  356. ctx.Data["Path"] = dirArray
  357. ctx.Data["Dirs"] = fileInfos
  358. ctx.Data["task"] = task
  359. ctx.Data["JobID"] = jobID
  360. ctx.HTML(200, tplCloudBrainShowModels)
  361. }
  362. func GetPublicImages(ctx *context.Context) {
  363. getImages(ctx, cloudbrain.Public)
  364. }
  365. func GetCustomImages(ctx *context.Context) {
  366. getImages(ctx, cloudbrain.Custom)
  367. }
  368. func getImages(ctx *context.Context, imageType string) {
  369. log.Info("Get images begin")
  370. page := ctx.QueryInt("page")
  371. size := ctx.QueryInt("size")
  372. name := ctx.Query("name")
  373. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  374. if err != nil {
  375. log.Error("Can not get images:%v", err)
  376. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  377. Count: 0,
  378. TotalPages: 0,
  379. ImageInfo: []*models.ImageInfo{},
  380. })
  381. } else {
  382. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  383. }
  384. log.Info("Get images end")
  385. }
  386. func getModelDirs(jobName string, parentDir string) (string, error) {
  387. var req string
  388. modelActualPath := setting.JobPath + jobName + "/model/"
  389. if parentDir == "" {
  390. req = "baseDir=" + modelActualPath
  391. } else {
  392. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  393. }
  394. return getDirs(req)
  395. }
  396. func CloudBrainDownloadModel(ctx *context.Context) {
  397. parentDir := ctx.Query("parentDir")
  398. fileName := ctx.Query("fileName")
  399. jobName := ctx.Query("jobName")
  400. filePath := "jobs/" + jobName + "/model/" + parentDir
  401. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  402. if err != nil {
  403. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  404. ctx.ServerError("PresignedGetURL", err)
  405. return
  406. }
  407. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  408. }
  409. func GetRate(ctx *context.Context) {
  410. var jobID = ctx.Params(":jobid")
  411. job, err := models.GetCloudbrainByJobID(jobID)
  412. if err != nil {
  413. ctx.ServerError("GetCloudbrainByJobID failed", err)
  414. return
  415. }
  416. if job.JobType == string(models.JobTypeBenchmark) {
  417. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  418. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  419. ctx.Redirect(setting.Snn4imagenetServerHost)
  420. } else {
  421. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  422. }
  423. }
  424. func downloadCode(repo *models.Repository, codePath string) error {
  425. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  426. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  427. return err
  428. }
  429. configFile, err := os.OpenFile(codePath + "/.git/config", os.O_RDWR, 0666)
  430. if err != nil {
  431. log.Error("open file(%s) failed:%v", codePath + "/,git/config", err)
  432. return err
  433. }
  434. defer configFile.Close()
  435. pos := int64(0)
  436. reader := bufio.NewReader(configFile)
  437. for {
  438. line, err := reader.ReadString('\n')
  439. if err != nil {
  440. if err == io.EOF {
  441. log.Error("not find the remote-url")
  442. return nil
  443. } else {
  444. log.Error("read error: %v", err)
  445. return err
  446. }
  447. }
  448. if strings.Contains(line, "url") && strings.Contains(line, ".git"){
  449. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  450. if len(line) > len(originUrl) {
  451. originUrl += strings.Repeat( " ", len(line) - len(originUrl))
  452. }
  453. bytes := []byte(originUrl)
  454. _, err := configFile.WriteAt(bytes, pos)
  455. if err != nil {
  456. log.Error("WriteAt failed:%v", err)
  457. return err
  458. }
  459. break
  460. }
  461. pos += int64(len(line))
  462. }
  463. return nil
  464. }
  465. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  466. err := os.MkdirAll(codePath, os.ModePerm)
  467. if err != nil {
  468. log.Error("mkdir codePath failed", err.Error())
  469. return err
  470. }
  471. command := "git clone " + gitPath + " " + codePath
  472. cmd := exec.Command("/bin/bash", "-c", command)
  473. output, err := cmd.Output()
  474. log.Info(string(output))
  475. if err != nil {
  476. log.Error("exec.Command(%s) failed:%v", command, err)
  477. return err
  478. }
  479. fileName := codePath + cloudbrain.TaskInfoName
  480. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  481. if err != nil {
  482. log.Error("OpenFile failed", err.Error())
  483. return err
  484. }
  485. defer f.Close()
  486. data, err := json.Marshal(models.TaskInfo{
  487. Username: repo.Owner.Name,
  488. TaskName: taskName,
  489. CodeName: repo.Name,
  490. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  491. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  492. GpuType: gpuType,
  493. })
  494. if err != nil {
  495. log.Error("json.Marshal failed", err.Error())
  496. return err
  497. }
  498. _, err = f.Write(data)
  499. if err != nil {
  500. log.Error("WriteString failed", err.Error())
  501. return err
  502. }
  503. return nil
  504. }