git_action_handler.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. // generate porter jwt token
  112. jwt, _ := token.GetTokenForAPI(userID, uint(projID))
  113. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  114. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  115. })
  116. if err != nil {
  117. app.handleErrorInternal(err, w)
  118. return nil
  119. }
  120. // create the commit in the git repo
  121. gaRunner := &actions.GithubActions{
  122. GitIntegration: gr,
  123. GitRepoName: repoSplit[1],
  124. GitRepoOwner: repoSplit[0],
  125. Repo: *app.Repo,
  126. GithubConf: app.GithubProjectConf,
  127. WebhookToken: release.WebhookToken,
  128. ProjectID: uint(projID),
  129. ReleaseName: name,
  130. DockerFilePath: gitAction.DockerfilePath,
  131. FolderPath: gitAction.FolderPath,
  132. ImageRepoURL: gitAction.ImageRepoURI,
  133. PorterToken: encoded,
  134. BuildEnv: form.BuildEnv,
  135. }
  136. _, err = gaRunner.Setup()
  137. if err != nil {
  138. app.handleErrorInternal(err, w)
  139. return nil
  140. }
  141. // handle write to the database
  142. ga, err := app.Repo.GitActionConfig.CreateGitActionConfig(gitAction)
  143. if err != nil {
  144. app.handleErrorDataWrite(err, w)
  145. return nil
  146. }
  147. app.Logger.Info().Msgf("New git action created: %d", ga.ID)
  148. return ga.Externalize()
  149. }