deploy_handler.go 12 KB

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