git_action_handler.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. "strings"
  9. "github.com/go-chi/chi"
  10. "github.com/porter-dev/porter/internal/auth/token"
  11. "github.com/porter-dev/porter/internal/forms"
  12. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  13. )
  14. // HandleCreateGitAction creates a new Github action in a repository for a given
  15. // release
  16. func (app *App) HandleCreateGitAction(w http.ResponseWriter, r *http.Request) {
  17. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  18. if err != nil || projID == 0 {
  19. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  20. return
  21. }
  22. vals, err := url.ParseQuery(r.URL.RawQuery)
  23. name := vals["name"][0]
  24. namespace := vals["namespace"][0]
  25. clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
  26. if err != nil {
  27. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  28. Code: ErrReleaseReadData,
  29. Errors: []string{"release not found"},
  30. }, w)
  31. }
  32. release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, namespace)
  33. if err != nil {
  34. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  35. Code: ErrReleaseReadData,
  36. Errors: []string{"release not found"},
  37. }, w)
  38. }
  39. form := &forms.CreateGitAction{
  40. ReleaseID: release.Model.ID,
  41. }
  42. // decode from JSON to form value
  43. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  44. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  45. return
  46. }
  47. // validate the form
  48. if err := app.validator.Struct(form); err != nil {
  49. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  50. return
  51. }
  52. // convert the form to a git action config
  53. gitAction, err := form.ToGitActionConfig()
  54. if err != nil {
  55. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  56. return
  57. }
  58. // read the git repo
  59. gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
  60. if err != nil {
  61. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  62. return
  63. }
  64. repoSplit := strings.Split(gitAction.GitRepo, "/")
  65. if len(repoSplit) != 2 {
  66. app.handleErrorFormDecoding(fmt.Errorf("invalid formatting of repo name"), ErrProjectDecode, w)
  67. return
  68. }
  69. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  70. if err != nil {
  71. http.Error(w, err.Error(), http.StatusInternalServerError)
  72. return
  73. }
  74. userID, _ := session.Values["user_id"].(uint)
  75. // generate porter jwt token
  76. jwt, _ := token.GetTokenForAPI(userID, uint(projID))
  77. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  78. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  79. })
  80. if err != nil {
  81. fmt.Println("ERROR GENERATING TOKEN", err)
  82. http.Error(w, err.Error(), http.StatusInternalServerError)
  83. return
  84. }
  85. // create the commit in the git repo
  86. gaRunner := &actions.GithubActions{
  87. GitIntegration: gr,
  88. GitRepoName: repoSplit[1],
  89. GitRepoOwner: repoSplit[0],
  90. Repo: *app.Repo,
  91. GithubConf: app.GithubConf,
  92. WebhookToken: release.WebhookToken,
  93. ProjectID: uint(projID),
  94. ReleaseName: name,
  95. DockerFilePath: gitAction.DockerfilePath,
  96. ImageRepoURL: gitAction.ImageRepoURI,
  97. PorterToken: encoded,
  98. }
  99. _, err = gaRunner.Setup()
  100. if err != nil {
  101. fmt.Println("ERROR RUNNING SETUP", err)
  102. http.Error(w, err.Error(), http.StatusInternalServerError)
  103. return
  104. }
  105. // handle write to the database
  106. ga, err := app.Repo.GitActionConfig.CreateGitActionConfig(gitAction)
  107. if err != nil {
  108. app.handleErrorDataWrite(err, w)
  109. return
  110. }
  111. app.Logger.Info().Msgf("New git action created: %d", ga.ID)
  112. w.WriteHeader(http.StatusCreated)
  113. gaExt := ga.Externalize()
  114. if err := json.NewEncoder(w).Encode(gaExt); err != nil {
  115. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  116. return
  117. }
  118. }