git_action_handler.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. // read the git repo
  95. gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
  96. if err != nil {
  97. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  98. return nil
  99. }
  100. repoSplit := strings.Split(gitAction.GitRepo, "/")
  101. if len(repoSplit) != 2 {
  102. app.handleErrorFormDecoding(fmt.Errorf("invalid formatting of repo name"), ErrProjectDecode, w)
  103. return nil
  104. }
  105. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  106. if err != nil {
  107. http.Error(w, err.Error(), http.StatusInternalServerError)
  108. return nil
  109. }
  110. userID, _ := session.Values["user_id"].(uint)
  111. if userID == 0 {
  112. tok := app.getTokenFromRequest(r)
  113. if tok != nil && tok.IBy != 0 {
  114. userID = tok.IBy
  115. } else if tok == nil || tok.IBy == 0 {
  116. http.Error(w, "no user id found in request", http.StatusInternalServerError)
  117. return nil
  118. }
  119. }
  120. // generate porter jwt token
  121. jwt, _ := token.GetTokenForAPI(userID, uint(projID))
  122. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  123. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  124. })
  125. if err != nil {
  126. app.handleErrorInternal(err, w)
  127. return nil
  128. }
  129. // create the commit in the git repo
  130. gaRunner := &actions.GithubActions{
  131. ServerURL: app.ServerConf.ServerURL,
  132. GitIntegration: gr,
  133. GitRepoName: repoSplit[1],
  134. GitRepoOwner: repoSplit[0],
  135. Repo: *app.Repo,
  136. GithubConf: app.GithubProjectConf,
  137. WebhookToken: release.WebhookToken,
  138. ProjectID: uint(projID),
  139. ReleaseName: name,
  140. GitBranch: gitAction.GitBranch,
  141. DockerFilePath: gitAction.DockerfilePath,
  142. FolderPath: gitAction.FolderPath,
  143. ImageRepoURL: gitAction.ImageRepoURI,
  144. PorterToken: encoded,
  145. BuildEnv: form.BuildEnv,
  146. }
  147. _, err = gaRunner.Setup()
  148. if err != nil {
  149. app.handleErrorInternal(err, w)
  150. return nil
  151. }
  152. // handle write to the database
  153. ga, err := app.Repo.GitActionConfig.CreateGitActionConfig(gitAction)
  154. if err != nil {
  155. app.handleErrorDataWrite(err, w)
  156. return nil
  157. }
  158. app.Logger.Info().Msgf("New git action created: %d", ga.ID)
  159. // update the release in the db with the image repo uri
  160. release.ImageRepoURI = gitAction.ImageRepoURI
  161. _, err = app.Repo.Release.UpdateRelease(release)
  162. if err != nil {
  163. app.handleErrorDataWrite(err, w)
  164. return nil
  165. }
  166. return ga.Externalize()
  167. }