git_action_handler.go 5.2 KB

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