git_action_handler.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. if reg.InfraID != 0 {
  78. _reg := registry.Registry(*reg)
  79. regAPI := &_reg
  80. // parse the name from the registry
  81. nameSpl := strings.Split(form.ImageRepoURI, "/")
  82. repoName := nameSpl[len(nameSpl)-1]
  83. err := regAPI.CreateRepository(*app.Repo, repoName)
  84. if err != nil {
  85. app.handleErrorInternal(err, w)
  86. return nil
  87. }
  88. }
  89. }
  90. // convert the form to a git action config
  91. gitAction, err := form.ToGitActionConfig()
  92. if err != nil {
  93. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  94. return nil
  95. }
  96. // read the git repo
  97. gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
  98. if err != nil {
  99. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  100. return nil
  101. }
  102. repoSplit := strings.Split(gitAction.GitRepo, "/")
  103. if len(repoSplit) != 2 {
  104. app.handleErrorFormDecoding(fmt.Errorf("invalid formatting of repo name"), ErrProjectDecode, w)
  105. return nil
  106. }
  107. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  108. if err != nil {
  109. http.Error(w, err.Error(), http.StatusInternalServerError)
  110. return nil
  111. }
  112. userID, _ := session.Values["user_id"].(uint)
  113. // generate porter jwt token
  114. jwt, _ := token.GetTokenForAPI(userID, uint(projID))
  115. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  116. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  117. })
  118. if err != nil {
  119. app.handleErrorInternal(err, w)
  120. return nil
  121. }
  122. // create the commit in the git repo
  123. gaRunner := &actions.GithubActions{
  124. GitIntegration: gr,
  125. GitRepoName: repoSplit[1],
  126. GitRepoOwner: repoSplit[0],
  127. Repo: *app.Repo,
  128. GithubConf: app.GithubProjectConf,
  129. WebhookToken: release.WebhookToken,
  130. ProjectID: uint(projID),
  131. ReleaseName: name,
  132. DockerFilePath: gitAction.DockerfilePath,
  133. ImageRepoURL: gitAction.ImageRepoURI,
  134. PorterToken: encoded,
  135. BuildEnv: form.BuildEnv,
  136. }
  137. _, err = gaRunner.Setup()
  138. if err != nil {
  139. app.handleErrorInternal(err, w)
  140. return nil
  141. }
  142. // handle write to the database
  143. ga, err := app.Repo.GitActionConfig.CreateGitActionConfig(gitAction)
  144. if err != nil {
  145. app.handleErrorDataWrite(err, w)
  146. return nil
  147. }
  148. app.Logger.Info().Msgf("New git action created: %d", ga.ID)
  149. return ga.Externalize()
  150. }