deploy_handler.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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/forms"
  11. "github.com/porter-dev/porter/internal/helm"
  12. "github.com/porter-dev/porter/internal/helm/loader"
  13. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  14. "github.com/porter-dev/porter/internal/models"
  15. "github.com/porter-dev/porter/internal/repository"
  16. "gopkg.in/yaml.v2"
  17. )
  18. // HandleDeployTemplate triggers a chart deployment from a template
  19. func (app *App) HandleDeployTemplate(w http.ResponseWriter, r *http.Request) {
  20. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  21. if err != nil || projID == 0 {
  22. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  23. return
  24. }
  25. name := chi.URLParam(r, "name")
  26. version := chi.URLParam(r, "version")
  27. // if version passed as latest, pass empty string to loader to get latest
  28. if version == "latest" {
  29. version = ""
  30. }
  31. getChartForm := &forms.ChartForm{
  32. Name: name,
  33. Version: version,
  34. RepoURL: app.ServerConf.DefaultApplicationHelmRepoURL,
  35. }
  36. // if a repo_url is passed as query param, it will be populated
  37. vals, err := url.ParseQuery(r.URL.RawQuery)
  38. if err != nil {
  39. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  40. return
  41. }
  42. getChartForm.PopulateRepoURLFromQueryParams(vals)
  43. chart, err := loader.LoadChartPublic(getChartForm.RepoURL, getChartForm.Name, getChartForm.Version)
  44. if err != nil {
  45. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  46. return
  47. }
  48. form := &forms.InstallChartTemplateForm{
  49. ReleaseForm: &forms.ReleaseForm{
  50. Form: &helm.Form{
  51. Repo: app.Repo,
  52. DigitalOceanOAuth: app.DOConf,
  53. },
  54. },
  55. ChartTemplateForm: &forms.ChartTemplateForm{},
  56. }
  57. form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
  58. vals,
  59. app.Repo.Cluster,
  60. )
  61. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  62. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  63. return
  64. }
  65. agent, err := app.getAgentFromReleaseForm(
  66. w,
  67. r,
  68. form.ReleaseForm,
  69. )
  70. if err != nil {
  71. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  72. return
  73. }
  74. registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(projID))
  75. if err != nil {
  76. app.handleErrorDataRead(err, w)
  77. return
  78. }
  79. conf := &helm.InstallChartConfig{
  80. Chart: chart,
  81. Name: form.ChartTemplateForm.Name,
  82. Namespace: form.ReleaseForm.Form.Namespace,
  83. Values: form.ChartTemplateForm.FormValues,
  84. Cluster: form.ReleaseForm.Cluster,
  85. Repo: *app.Repo,
  86. Registries: registries,
  87. }
  88. rel, err := agent.InstallChart(conf, app.DOConf)
  89. if err != nil {
  90. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  91. Code: ErrReleaseDeploy,
  92. Errors: []string{"error installing a new chart: " + err.Error()},
  93. }, w)
  94. return
  95. }
  96. token, err := repository.GenerateRandomBytes(16)
  97. if err != nil {
  98. app.handleErrorInternal(err, w)
  99. return
  100. }
  101. // create release with webhook token in db
  102. repository := rel.Config["image"].(map[string]interface{})["repository"]
  103. repoStr, ok := repository.(string)
  104. if !ok {
  105. app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
  106. return
  107. }
  108. release := &models.Release{
  109. ClusterID: form.ReleaseForm.Form.Cluster.ID,
  110. ProjectID: form.ReleaseForm.Form.Cluster.ProjectID,
  111. Namespace: form.ReleaseForm.Form.Namespace,
  112. Name: form.ChartTemplateForm.Name,
  113. WebhookToken: token,
  114. ImageRepoURI: repoStr,
  115. }
  116. _, err = app.Repo.Release.CreateRelease(release)
  117. if err != nil {
  118. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  119. Code: ErrReleaseDeploy,
  120. Errors: []string{"error creating a webhook: " + err.Error()},
  121. }, w)
  122. }
  123. // if github action config is linked, call the github action config handler
  124. if form.GithubActionConfig != nil {
  125. gaForm := &forms.CreateGitAction{
  126. ReleaseID: release.ID,
  127. GitRepo: form.GithubActionConfig.GitRepo,
  128. GitBranch: form.GithubActionConfig.GitBranch,
  129. ImageRepoURI: form.GithubActionConfig.ImageRepoURI,
  130. DockerfilePath: form.GithubActionConfig.DockerfilePath,
  131. GitRepoID: form.GithubActionConfig.GitRepoID,
  132. BuildEnv: form.GithubActionConfig.BuildEnv,
  133. RegistryID: form.GithubActionConfig.RegistryID,
  134. }
  135. // validate the form
  136. if err := app.validator.Struct(form); err != nil {
  137. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  138. return
  139. }
  140. app.createGitActionFromForm(projID, release, form.ChartTemplateForm.Name, gaForm, w, r)
  141. }
  142. w.WriteHeader(http.StatusOK)
  143. }
  144. // HandleUninstallTemplate triggers a chart deployment from a template
  145. func (app *App) HandleUninstallTemplate(w http.ResponseWriter, r *http.Request) {
  146. name := chi.URLParam(r, "name")
  147. vals, err := url.ParseQuery(r.URL.RawQuery)
  148. if err != nil {
  149. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  150. return
  151. }
  152. form := &forms.GetReleaseForm{
  153. ReleaseForm: &forms.ReleaseForm{
  154. Form: &helm.Form{
  155. Repo: app.Repo,
  156. },
  157. },
  158. Name: name,
  159. }
  160. agent, err := app.getAgentFromQueryParams(
  161. w,
  162. r,
  163. form.ReleaseForm,
  164. form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
  165. )
  166. // errors are handled in app.getAgentFromQueryParams
  167. if err != nil {
  168. return
  169. }
  170. resp, err := agent.UninstallChart(name)
  171. if err != nil {
  172. return
  173. }
  174. // update the github actions env if the release exists and is built from source
  175. if cName := resp.Release.Chart.Metadata.Name; cName == "job" || cName == "web" || cName == "worker" {
  176. clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
  177. if err != nil {
  178. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  179. Code: ErrReleaseReadData,
  180. Errors: []string{"release not found"},
  181. }, w)
  182. }
  183. release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, resp.Release.Namespace)
  184. if release != nil {
  185. gitAction := release.GitActionConfig
  186. if gitAction.ID != 0 {
  187. // parse env into build env
  188. cEnv := &ContainerEnvConfig{}
  189. rawValues, err := yaml.Marshal(resp.Release.Config)
  190. if err != nil {
  191. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  192. Code: ErrReleaseReadData,
  193. Errors: []string{"could not get values of previous revision"},
  194. }, w)
  195. }
  196. yaml.Unmarshal(rawValues, cEnv)
  197. gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
  198. if err != nil {
  199. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  200. Code: ErrReleaseReadData,
  201. Errors: []string{"github repo integration not found"},
  202. }, w)
  203. }
  204. repoSplit := strings.Split(gitAction.GitRepo, "/")
  205. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  206. if err != nil || projID == 0 {
  207. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  208. return
  209. }
  210. gaRunner := &actions.GithubActions{
  211. ServerURL: app.ServerConf.ServerURL,
  212. GitIntegration: gr,
  213. GitRepoName: repoSplit[1],
  214. GitRepoOwner: repoSplit[0],
  215. Repo: *app.Repo,
  216. GithubConf: app.GithubProjectConf,
  217. WebhookToken: release.WebhookToken,
  218. ProjectID: uint(projID),
  219. ReleaseName: name,
  220. GitBranch: gitAction.GitBranch,
  221. DockerFilePath: gitAction.DockerfilePath,
  222. FolderPath: gitAction.FolderPath,
  223. ImageRepoURL: gitAction.ImageRepoURI,
  224. BuildEnv: cEnv.Container.Env.Normal,
  225. }
  226. err = gaRunner.Cleanup()
  227. if err != nil {
  228. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  229. Code: ErrReleaseReadData,
  230. Errors: []string{"could not remove github action"},
  231. }, w)
  232. }
  233. }
  234. }
  235. }
  236. w.WriteHeader(http.StatusOK)
  237. return
  238. }