deploy_handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "github.com/go-chi/chi"
  11. "github.com/porter-dev/porter/internal/forms"
  12. "github.com/porter-dev/porter/internal/helm"
  13. "github.com/porter-dev/porter/internal/helm/loader"
  14. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  15. "github.com/porter-dev/porter/internal/models"
  16. "github.com/porter-dev/porter/internal/repository"
  17. "gopkg.in/yaml.v2"
  18. )
  19. // HandleDeployTemplate triggers a chart deployment from a template
  20. func (app *App) HandleDeployTemplate(w http.ResponseWriter, r *http.Request) {
  21. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  22. if err != nil || projID == 0 {
  23. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  24. return
  25. }
  26. name := chi.URLParam(r, "name")
  27. version := chi.URLParam(r, "version")
  28. // if version passed as latest, pass empty string to loader to get latest
  29. if version == "latest" {
  30. version = ""
  31. }
  32. getChartForm := &forms.ChartForm{
  33. Name: name,
  34. Version: version,
  35. RepoURL: app.ServerConf.DefaultApplicationHelmRepoURL,
  36. }
  37. // if a repo_url is passed as query param, it will be populated
  38. vals, err := url.ParseQuery(r.URL.RawQuery)
  39. if err != nil {
  40. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  41. return
  42. }
  43. getChartForm.PopulateRepoURLFromQueryParams(vals)
  44. chart, err := loader.LoadChartPublic(getChartForm.RepoURL, getChartForm.Name, getChartForm.Version)
  45. if err != nil {
  46. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  47. return
  48. }
  49. form := &forms.InstallChartTemplateForm{
  50. ReleaseForm: &forms.ReleaseForm{
  51. Form: &helm.Form{
  52. Repo: app.Repo,
  53. DigitalOceanOAuth: app.DOConf,
  54. },
  55. },
  56. ChartTemplateForm: &forms.ChartTemplateForm{},
  57. }
  58. form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
  59. vals,
  60. app.Repo.Cluster,
  61. )
  62. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  63. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  64. return
  65. }
  66. agent, err := app.getAgentFromReleaseForm(
  67. w,
  68. r,
  69. form.ReleaseForm,
  70. )
  71. if err != nil {
  72. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  73. return
  74. }
  75. registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(projID))
  76. if err != nil {
  77. app.handleErrorDataRead(err, w)
  78. return
  79. }
  80. conf := &helm.InstallChartConfig{
  81. Chart: chart,
  82. Name: form.ChartTemplateForm.Name,
  83. Namespace: form.ReleaseForm.Form.Namespace,
  84. Values: form.ChartTemplateForm.FormValues,
  85. Cluster: form.ReleaseForm.Cluster,
  86. Repo: *app.Repo,
  87. Registries: registries,
  88. }
  89. rel, err := agent.InstallChart(conf, app.DOConf)
  90. if err != nil {
  91. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  92. Code: ErrReleaseDeploy,
  93. Errors: []string{"error installing a new chart: " + err.Error()},
  94. }, w)
  95. return
  96. }
  97. token, err := repository.GenerateRandomBytes(16)
  98. if err != nil {
  99. app.handleErrorInternal(err, w)
  100. return
  101. }
  102. // create release with webhook token in db
  103. image, ok := rel.Config["image"].(map[string]interface{})
  104. if !ok {
  105. app.handleErrorInternal(fmt.Errorf("Could not find field image in config"), w)
  106. return
  107. }
  108. repository := image["repository"]
  109. repoStr, ok := repository.(string)
  110. if !ok {
  111. app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
  112. return
  113. }
  114. release := &models.Release{
  115. ClusterID: form.ReleaseForm.Form.Cluster.ID,
  116. ProjectID: form.ReleaseForm.Form.Cluster.ProjectID,
  117. Namespace: form.ReleaseForm.Form.Namespace,
  118. Name: form.ChartTemplateForm.Name,
  119. WebhookToken: token,
  120. ImageRepoURI: repoStr,
  121. }
  122. _, err = app.Repo.Release.CreateRelease(release)
  123. if err != nil {
  124. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  125. Code: ErrReleaseDeploy,
  126. Errors: []string{"error creating a webhook: " + err.Error()},
  127. }, w)
  128. }
  129. // if github action config is linked, call the github action config handler
  130. if form.GithubActionConfig != nil {
  131. gaForm := &forms.CreateGitAction{
  132. ReleaseID: release.ID,
  133. GitRepo: form.GithubActionConfig.GitRepo,
  134. GitBranch: form.GithubActionConfig.GitBranch,
  135. ImageRepoURI: form.GithubActionConfig.ImageRepoURI,
  136. DockerfilePath: form.GithubActionConfig.DockerfilePath,
  137. GitRepoID: form.GithubActionConfig.GitRepoID,
  138. RegistryID: form.GithubActionConfig.RegistryID,
  139. }
  140. // validate the form
  141. if err := app.validator.Struct(form); err != nil {
  142. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  143. return
  144. }
  145. app.createGitActionFromForm(projID, release, form.ChartTemplateForm.Name, gaForm, w, r)
  146. }
  147. w.WriteHeader(http.StatusOK)
  148. }
  149. // HandleDeployAddon triggers a addon deployment from a template
  150. func (app *App) HandleDeployAddon(w http.ResponseWriter, r *http.Request) {
  151. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  152. if err != nil || projID == 0 {
  153. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  154. return
  155. }
  156. name := chi.URLParam(r, "name")
  157. version := chi.URLParam(r, "version")
  158. // if version passed as latest, pass empty string to loader to get latest
  159. if version == "latest" {
  160. version = ""
  161. }
  162. getChartForm := &forms.ChartForm{
  163. Name: name,
  164. Version: version,
  165. RepoURL: app.ServerConf.DefaultApplicationHelmRepoURL,
  166. }
  167. // if a repo_url is passed as query param, it will be populated
  168. vals, err := url.ParseQuery(r.URL.RawQuery)
  169. if err != nil {
  170. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  171. return
  172. }
  173. getChartForm.PopulateRepoURLFromQueryParams(vals)
  174. chart, err := loader.LoadChartPublic(getChartForm.RepoURL, getChartForm.Name, getChartForm.Version)
  175. if err != nil {
  176. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  177. return
  178. }
  179. form := &forms.InstallChartTemplateForm{
  180. ReleaseForm: &forms.ReleaseForm{
  181. Form: &helm.Form{
  182. Repo: app.Repo,
  183. DigitalOceanOAuth: app.DOConf,
  184. },
  185. },
  186. ChartTemplateForm: &forms.ChartTemplateForm{},
  187. }
  188. form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
  189. vals,
  190. app.Repo.Cluster,
  191. )
  192. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  193. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  194. return
  195. }
  196. agent, err := app.getAgentFromReleaseForm(
  197. w,
  198. r,
  199. form.ReleaseForm,
  200. )
  201. if err != nil {
  202. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  203. return
  204. }
  205. registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(projID))
  206. if err != nil {
  207. app.handleErrorDataRead(err, w)
  208. return
  209. }
  210. conf := &helm.InstallChartConfig{
  211. Chart: chart,
  212. Name: form.ChartTemplateForm.Name,
  213. Namespace: form.ReleaseForm.Form.Namespace,
  214. Values: form.ChartTemplateForm.FormValues,
  215. Cluster: form.ReleaseForm.Cluster,
  216. Repo: *app.Repo,
  217. Registries: registries,
  218. }
  219. _, err = agent.InstallChart(conf, app.DOConf)
  220. if err != nil {
  221. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  222. Code: ErrReleaseDeploy,
  223. Errors: []string{"error installing a new chart: " + err.Error()},
  224. }, w)
  225. return
  226. }
  227. w.WriteHeader(http.StatusOK)
  228. }
  229. // HandleUninstallTemplate triggers a chart deployment from a template
  230. func (app *App) HandleUninstallTemplate(w http.ResponseWriter, r *http.Request) {
  231. name := chi.URLParam(r, "name")
  232. vals, err := url.ParseQuery(r.URL.RawQuery)
  233. if err != nil {
  234. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  235. return
  236. }
  237. form := &forms.GetReleaseForm{
  238. ReleaseForm: &forms.ReleaseForm{
  239. Form: &helm.Form{
  240. Repo: app.Repo,
  241. },
  242. },
  243. Name: name,
  244. }
  245. agent, err := app.getAgentFromQueryParams(
  246. w,
  247. r,
  248. form.ReleaseForm,
  249. form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
  250. )
  251. // errors are handled in app.getAgentFromQueryParams
  252. if err != nil {
  253. return
  254. }
  255. resp, err := agent.UninstallChart(name)
  256. if err != nil {
  257. return
  258. }
  259. // update the github actions env if the release exists and is built from source
  260. if cName := resp.Release.Chart.Metadata.Name; cName == "job" || cName == "web" || cName == "worker" {
  261. clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
  262. if err != nil {
  263. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  264. Code: ErrReleaseReadData,
  265. Errors: []string{"release not found"},
  266. }, w)
  267. }
  268. release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, resp.Release.Namespace)
  269. if release != nil {
  270. gitAction := release.GitActionConfig
  271. if gitAction.ID != 0 {
  272. // parse env into build env
  273. cEnv := &ContainerEnvConfig{}
  274. rawValues, err := yaml.Marshal(resp.Release.Config)
  275. if err != nil {
  276. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  277. Code: ErrReleaseReadData,
  278. Errors: []string{"could not get values of previous revision"},
  279. }, w)
  280. }
  281. yaml.Unmarshal(rawValues, cEnv)
  282. gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
  283. if err != nil {
  284. if err != gorm.ErrRecordNotFound {
  285. app.handleErrorInternal(err, w)
  286. return
  287. }
  288. gr = nil
  289. }
  290. repoSplit := strings.Split(gitAction.GitRepo, "/")
  291. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  292. if err != nil || projID == 0 {
  293. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  294. return
  295. }
  296. gaRunner := &actions.GithubActions{
  297. ServerURL: app.ServerConf.ServerURL,
  298. GithubOAuthIntegration: gr,
  299. GithubAppID: app.GithubAppConf.AppID,
  300. GithubAppSecretPath: app.GithubAppConf.SecretPath,
  301. GithubInstallationID: gitAction.GithubInstallationID,
  302. GitRepoName: repoSplit[1],
  303. GitRepoOwner: repoSplit[0],
  304. Repo: *app.Repo,
  305. GithubConf: app.GithubProjectConf,
  306. ProjectID: uint(projID),
  307. ReleaseName: name,
  308. GitBranch: gitAction.GitBranch,
  309. DockerFilePath: gitAction.DockerfilePath,
  310. FolderPath: gitAction.FolderPath,
  311. ImageRepoURL: gitAction.ImageRepoURI,
  312. BuildEnv: cEnv.Container.Env.Normal,
  313. ClusterID: release.ClusterID,
  314. }
  315. err = gaRunner.Cleanup()
  316. if err != nil {
  317. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  318. Code: ErrReleaseReadData,
  319. Errors: []string{"could not remove github action"},
  320. }, w)
  321. }
  322. }
  323. }
  324. }
  325. w.WriteHeader(http.StatusOK)
  326. return
  327. }