| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470 |
- package api
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "gorm.io/gorm"
- "github.com/go-chi/chi"
- "github.com/porter-dev/porter/internal/analytics"
- "github.com/porter-dev/porter/internal/forms"
- "github.com/porter-dev/porter/internal/helm"
- "github.com/porter-dev/porter/internal/helm/loader"
- "github.com/porter-dev/porter/internal/integrations/ci/actions"
- "github.com/porter-dev/porter/internal/models"
- "github.com/porter-dev/porter/internal/oauth"
- "github.com/porter-dev/porter/internal/repository"
- "gopkg.in/yaml.v2"
- )
- // HandleDeployTemplate triggers a chart deployment from a template
- func (app *App) HandleDeployTemplate(w http.ResponseWriter, r *http.Request) {
- projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
- userID, err := app.getUserIDFromRequest(r)
- flowID := oauth.CreateRandomState()
- if err != nil || projID == 0 {
- app.handleErrorFormDecoding(err, ErrProjectDecode, w)
- return
- }
- name := chi.URLParam(r, "name")
- version := chi.URLParam(r, "version")
- // if version passed as latest, pass empty string to loader to get latest
- if version == "latest" {
- version = ""
- }
- getChartForm := &forms.ChartForm{
- Name: name,
- Version: version,
- RepoURL: app.ServerConf.DefaultApplicationHelmRepoURL,
- }
- // if a repo_url is passed as query param, it will be populated
- vals, err := url.ParseQuery(r.URL.RawQuery)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- app.AnalyticsClient.Track(analytics.ApplicationLaunchStartTrack(
- &analytics.ApplicationLaunchStartTrackOpts{
- ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(userID, uint(projID), uint(clusterID)),
- FlowID: flowID,
- },
- ))
- getChartForm.PopulateRepoURLFromQueryParams(vals)
- chart, err := loader.LoadChartPublic(getChartForm.RepoURL, getChartForm.Name, getChartForm.Version)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- form := &forms.InstallChartTemplateForm{
- ReleaseForm: &forms.ReleaseForm{
- Form: &helm.Form{
- Repo: app.Repo,
- DigitalOceanOAuth: app.DOConf,
- },
- },
- ChartTemplateForm: &forms.ChartTemplateForm{},
- }
- form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
- vals,
- app.Repo.Cluster(),
- )
- if err := json.NewDecoder(r.Body).Decode(form); err != nil {
- app.handleErrorFormDecoding(err, ErrUserDecode, w)
- return
- }
- agent, err := app.getAgentFromReleaseForm(
- w,
- r,
- form.ReleaseForm,
- )
- if err != nil {
- app.handleErrorFormDecoding(err, ErrUserDecode, w)
- return
- }
- registries, err := app.Repo.Registry().ListRegistriesByProjectID(uint(projID))
- if err != nil {
- app.handleErrorDataRead(err, w)
- return
- }
- conf := &helm.InstallChartConfig{
- Chart: chart,
- Name: form.ChartTemplateForm.Name,
- Namespace: form.ReleaseForm.Form.Namespace,
- Values: form.ChartTemplateForm.FormValues,
- Cluster: form.ReleaseForm.Cluster,
- Repo: app.Repo,
- Registries: registries,
- }
- rel, err := agent.InstallChart(conf, app.DOConf)
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseDeploy,
- Errors: []string{"error installing a new chart: " + err.Error()},
- }, w)
- return
- }
- token, err := repository.GenerateRandomBytes(16)
- if err != nil {
- app.handleErrorInternal(err, w)
- return
- }
- // create release with webhook token in db
- image, ok := rel.Config["image"].(map[string]interface{})
- if !ok {
- app.handleErrorInternal(fmt.Errorf("Could not find field image in config"), w)
- return
- }
- repository := image["repository"]
- repoStr, ok := repository.(string)
- if !ok {
- app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
- return
- }
- release := &models.Release{
- ClusterID: form.ReleaseForm.Form.Cluster.ID,
- ProjectID: form.ReleaseForm.Form.Cluster.ProjectID,
- Namespace: form.ReleaseForm.Form.Namespace,
- Name: form.ChartTemplateForm.Name,
- WebhookToken: token,
- ImageRepoURI: repoStr,
- }
- _, err = app.Repo.Release().CreateRelease(release)
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseDeploy,
- Errors: []string{"error creating a webhook: " + err.Error()},
- }, w)
- }
- // if github action config is linked, call the github action config handler
- if form.GithubActionConfig != nil {
- gaForm := &forms.CreateGitAction{
- Release: release,
- GitRepo: form.GithubActionConfig.GitRepo,
- GitBranch: form.GithubActionConfig.GitBranch,
- ImageRepoURI: form.GithubActionConfig.ImageRepoURI,
- DockerfilePath: form.GithubActionConfig.DockerfilePath,
- GitRepoID: form.GithubActionConfig.GitRepoID,
- RegistryID: form.GithubActionConfig.RegistryID,
- ShouldGenerateOnly: false,
- ShouldCreateWorkflow: form.GithubActionConfig.ShouldCreateWorkflow,
- }
- // validate the form
- if err := app.validator.Struct(form); err != nil {
- app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
- return
- }
- app.createGitActionFromForm(projID, clusterID, form.ChartTemplateForm.Name, form.ReleaseForm.Form.Namespace, gaForm, w, r)
- }
- app.AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
- &analytics.ApplicationLaunchSuccessTrackOpts{
- ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
- userID,
- uint(projID),
- uint(clusterID),
- release.Name,
- release.Namespace,
- chart.Metadata.Name,
- ),
- FlowID: flowID,
- },
- ))
- w.WriteHeader(http.StatusOK)
- }
- // HandleDeployAddon triggers a addon deployment from a template
- func (app *App) HandleDeployAddon(w http.ResponseWriter, r *http.Request) {
- projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
- userID, err := app.getUserIDFromRequest(r)
- flowID := oauth.CreateRandomState()
- if err != nil || projID == 0 {
- app.handleErrorFormDecoding(err, ErrProjectDecode, w)
- return
- }
- name := chi.URLParam(r, "name")
- version := chi.URLParam(r, "version")
- // if version passed as latest, pass empty string to loader to get latest
- if version == "latest" {
- version = ""
- }
- getChartForm := &forms.ChartForm{
- Name: name,
- Version: version,
- RepoURL: app.ServerConf.DefaultApplicationHelmRepoURL,
- }
- // if a repo_url is passed as query param, it will be populated
- vals, err := url.ParseQuery(r.URL.RawQuery)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- getChartForm.PopulateRepoURLFromQueryParams(vals)
- chart, err := loader.LoadChartPublic(getChartForm.RepoURL, getChartForm.Name, getChartForm.Version)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- form := &forms.InstallChartTemplateForm{
- ReleaseForm: &forms.ReleaseForm{
- Form: &helm.Form{
- Repo: app.Repo,
- DigitalOceanOAuth: app.DOConf,
- },
- },
- ChartTemplateForm: &forms.ChartTemplateForm{},
- }
- form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
- vals,
- app.Repo.Cluster(),
- )
- if err := json.NewDecoder(r.Body).Decode(form); err != nil {
- app.handleErrorFormDecoding(err, ErrUserDecode, w)
- return
- }
- app.AnalyticsClient.Track(analytics.ApplicationLaunchStartTrack(
- &analytics.ApplicationLaunchStartTrackOpts{
- ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(userID, uint(projID), uint(form.ReleaseForm.Cluster.ID)),
- FlowID: flowID,
- },
- ))
- agent, err := app.getAgentFromReleaseForm(
- w,
- r,
- form.ReleaseForm,
- )
- if err != nil {
- app.handleErrorFormDecoding(err, ErrUserDecode, w)
- return
- }
- registries, err := app.Repo.Registry().ListRegistriesByProjectID(uint(projID))
- if err != nil {
- app.handleErrorDataRead(err, w)
- return
- }
- conf := &helm.InstallChartConfig{
- Chart: chart,
- Name: form.ChartTemplateForm.Name,
- Namespace: form.ReleaseForm.Form.Namespace,
- Values: form.ChartTemplateForm.FormValues,
- Cluster: form.ReleaseForm.Cluster,
- Repo: app.Repo,
- Registries: registries,
- }
- rel, err := agent.InstallChart(conf, app.DOConf)
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseDeploy,
- Errors: []string{"error installing a new chart: " + err.Error()},
- }, w)
- return
- }
- app.AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
- &analytics.ApplicationLaunchSuccessTrackOpts{
- ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
- userID,
- uint(projID),
- uint(form.ReleaseForm.Cluster.ID),
- rel.Name,
- rel.Namespace,
- chart.Metadata.Name,
- ),
- FlowID: flowID,
- },
- ))
- w.WriteHeader(http.StatusOK)
- }
- // HandleUninstallTemplate triggers a chart deployment from a template
- func (app *App) HandleUninstallTemplate(w http.ResponseWriter, r *http.Request) {
- name := chi.URLParam(r, "name")
- vals, err := url.ParseQuery(r.URL.RawQuery)
- if err != nil {
- app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
- return
- }
- form := &forms.GetReleaseForm{
- ReleaseForm: &forms.ReleaseForm{
- Form: &helm.Form{
- Repo: app.Repo,
- DigitalOceanOAuth: app.DOConf,
- },
- },
- Name: name,
- }
- agent, err := app.getAgentFromQueryParams(
- w,
- r,
- form.ReleaseForm,
- form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
- )
- // errors are handled in app.getAgentFromQueryParams
- if err != nil {
- return
- }
- resp, err := agent.UninstallChart(name)
- if err != nil {
- return
- }
- // update the github actions env if the release exists and is built from source
- if cName := resp.Release.Chart.Metadata.Name; cName == "job" || cName == "web" || cName == "worker" {
- clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseReadData,
- Errors: []string{"release not found"},
- }, w)
- }
- release, err := app.Repo.Release().ReadRelease(uint(clusterID), name, resp.Release.Namespace)
- if release != nil {
- gitAction := release.GitActionConfig
- if gitAction.ID != 0 {
- // parse env into build env
- cEnv := &ContainerEnvConfig{}
- rawValues, err := yaml.Marshal(resp.Release.Config)
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseReadData,
- Errors: []string{"could not get values of previous revision"},
- }, w)
- }
- yaml.Unmarshal(rawValues, cEnv)
- gr, err := app.Repo.GitRepo().ReadGitRepo(gitAction.GitRepoID)
- if err != nil {
- if err != gorm.ErrRecordNotFound {
- app.handleErrorInternal(err, w)
- return
- }
- gr = nil
- }
- repoSplit := strings.Split(gitAction.GitRepo, "/")
- projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
- if err != nil || projID == 0 {
- app.handleErrorFormDecoding(err, ErrProjectDecode, w)
- return
- }
- gaRunner := &actions.GithubActions{
- ServerURL: app.ServerConf.ServerURL,
- GithubOAuthIntegration: gr,
- GithubAppID: app.GithubAppConf.AppID,
- GithubAppSecretPath: app.GithubAppConf.SecretPath,
- GithubInstallationID: gitAction.GithubInstallationID,
- GitRepoName: repoSplit[1],
- GitRepoOwner: repoSplit[0],
- Repo: app.Repo,
- GithubConf: app.GithubProjectConf,
- ProjectID: uint(projID),
- ReleaseName: name,
- ReleaseNamespace: release.Namespace,
- GitBranch: gitAction.GitBranch,
- DockerFilePath: gitAction.DockerfilePath,
- FolderPath: gitAction.FolderPath,
- ImageRepoURL: gitAction.ImageRepoURI,
- BuildEnv: cEnv.Container.Env.Normal,
- ClusterID: release.ClusterID,
- Version: gitAction.Version,
- }
- err = gaRunner.Cleanup()
- if err != nil {
- app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
- Code: ErrReleaseReadData,
- Errors: []string{"could not remove github action"},
- }, w)
- }
- }
- }
- }
- w.WriteHeader(http.StatusOK)
- return
- }
|