git_action_handler.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "github.com/porter-dev/porter/internal/models"
  14. "github.com/porter-dev/porter/internal/registry"
  15. )
  16. // HandleCreateGitAction creates a new Github action in a repository for a given
  17. // release
  18. func (app *App) HandleCreateGitAction(w http.ResponseWriter, r *http.Request) {
  19. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  20. if err != nil || projID == 0 {
  21. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  22. return
  23. }
  24. vals, err := url.ParseQuery(r.URL.RawQuery)
  25. name := vals["name"][0]
  26. namespace := vals["namespace"][0]
  27. clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
  28. if err != nil {
  29. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  30. Code: ErrReleaseReadData,
  31. Errors: []string{"release not found"},
  32. }, w)
  33. }
  34. release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, namespace)
  35. if err != nil {
  36. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  37. Code: ErrReleaseReadData,
  38. Errors: []string{"release not found"},
  39. }, w)
  40. }
  41. form := &forms.CreateGitAction{
  42. ReleaseID: release.Model.ID,
  43. }
  44. // decode from JSON to form value
  45. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  46. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  47. return
  48. }
  49. gaExt := app.createGitActionFromForm(projID, release, name, form, w, r)
  50. w.WriteHeader(http.StatusCreated)
  51. if err := json.NewEncoder(w).Encode(gaExt); err != nil {
  52. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  53. return
  54. }
  55. }
  56. func (app *App) createGitActionFromForm(
  57. projID uint64,
  58. release *models.Release,
  59. name string,
  60. form *forms.CreateGitAction,
  61. w http.ResponseWriter,
  62. r *http.Request,
  63. ) *models.GitActionConfigExternal {
  64. // validate the form
  65. if err := app.validator.Struct(form); err != nil {
  66. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  67. return nil
  68. }
  69. // if the registry was provisioned through Porter, create a repository if necessary
  70. if form.RegistryID != 0 {
  71. // read the registry
  72. reg, err := app.Repo.Registry.ReadRegistry(form.RegistryID)
  73. if err != nil {
  74. app.handleErrorDataRead(err, w)
  75. return nil
  76. }
  77. _reg := registry.Registry(*reg)
  78. regAPI := &_reg
  79. // parse the name from the registry
  80. nameSpl := strings.Split(form.ImageRepoURI, "/")
  81. repoName := nameSpl[len(nameSpl)-1]
  82. err = regAPI.CreateRepository(*app.Repo, repoName)
  83. if err != nil {
  84. app.handleErrorInternal(err, w)
  85. return nil
  86. }
  87. }
  88. // convert the form to a git action config
  89. gitAction, err := form.ToGitActionConfig()
  90. if err != nil {
  91. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  92. return nil
  93. }
  94. repoSplit := strings.Split(gitAction.GitRepo, "/")
  95. if len(repoSplit) != 2 {
  96. app.handleErrorFormDecoding(fmt.Errorf("invalid formatting of repo name"), ErrProjectDecode, w)
  97. return nil
  98. }
  99. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  100. if err != nil {
  101. http.Error(w, err.Error(), http.StatusInternalServerError)
  102. return nil
  103. }
  104. userID, _ := session.Values["user_id"].(uint)
  105. if userID == 0 {
  106. tok := app.getTokenFromRequest(r)
  107. if tok != nil && tok.IBy != 0 {
  108. userID = tok.IBy
  109. } else if tok == nil || tok.IBy == 0 {
  110. http.Error(w, "no user id found in request", http.StatusInternalServerError)
  111. return nil
  112. }
  113. }
  114. // generate porter jwt token
  115. jwt, _ := token.GetTokenForAPI(userID, uint(projID))
  116. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  117. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  118. })
  119. if err != nil {
  120. app.handleErrorInternal(err, w)
  121. return nil
  122. }
  123. // create the commit in the git repo
  124. gaRunner := &actions.GithubActions{
  125. ServerURL: app.ServerConf.ServerURL,
  126. GithubOAuthIntegration: nil,
  127. GithubAppID: app.GithubAppConf.AppID,
  128. GithubInstallationID: form.GitRepoID,
  129. GitRepoName: repoSplit[1],
  130. GitRepoOwner: repoSplit[0],
  131. Repo: *app.Repo,
  132. GithubConf: app.GithubProjectConf,
  133. WebhookToken: release.WebhookToken,
  134. ProjectID: uint(projID),
  135. ReleaseName: name,
  136. GitBranch: gitAction.GitBranch,
  137. DockerFilePath: gitAction.DockerfilePath,
  138. FolderPath: gitAction.FolderPath,
  139. ImageRepoURL: gitAction.ImageRepoURI,
  140. PorterToken: encoded,
  141. BuildEnv: form.BuildEnv,
  142. }
  143. _, err = gaRunner.Setup()
  144. if err != nil {
  145. app.handleErrorInternal(err, w)
  146. return nil
  147. }
  148. // handle write to the database
  149. ga, err := app.Repo.GitActionConfig.CreateGitActionConfig(gitAction)
  150. if err != nil {
  151. app.handleErrorDataWrite(err, w)
  152. return nil
  153. }
  154. app.Logger.Info().Msgf("New git action created: %d", ga.ID)
  155. // update the release in the db with the image repo uri
  156. release.ImageRepoURI = gitAction.ImageRepoURI
  157. _, err = app.Repo.Release.UpdateRelease(release)
  158. if err != nil {
  159. app.handleErrorDataWrite(err, w)
  160. return nil
  161. }
  162. return ga.Externalize()
  163. }