update_environment_settings.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "reflect"
  8. "strings"
  9. "github.com/porter-dev/porter/api/server/authz"
  10. "github.com/porter-dev/porter/api/server/handlers"
  11. "github.com/porter-dev/porter/api/server/shared"
  12. "github.com/porter-dev/porter/api/server/shared/apierrors"
  13. "github.com/porter-dev/porter/api/server/shared/config"
  14. "github.com/porter-dev/porter/api/server/shared/requestutils"
  15. "github.com/porter-dev/porter/api/types"
  16. "github.com/porter-dev/porter/internal/models"
  17. "gorm.io/gorm"
  18. )
  19. type UpdateEnvironmentSettingsHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. authz.KubernetesAgentGetter
  22. }
  23. func NewUpdateEnvironmentSettingsHandler(
  24. config *config.Config,
  25. decoderValidator shared.RequestDecoderValidator,
  26. writer shared.ResultWriter,
  27. ) *UpdateEnvironmentSettingsHandler {
  28. return &UpdateEnvironmentSettingsHandler{
  29. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  30. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  31. }
  32. }
  33. func (c *UpdateEnvironmentSettingsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  34. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  35. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  36. envID, reqErr := requestutils.GetURLParamUint(r, "environment_id")
  37. if reqErr != nil {
  38. c.HandleAPIError(w, r, reqErr)
  39. return
  40. }
  41. request := &types.UpdateEnvironmentSettingsRequest{}
  42. if ok := c.DecodeAndValidate(w, r, request); !ok {
  43. return
  44. }
  45. env, err := c.Repo().Environment().ReadEnvironmentByID(project.ID, cluster.ID, envID)
  46. if err != nil {
  47. if errors.Is(err, gorm.ErrRecordNotFound) {
  48. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no such environment with ID: %d", envID)))
  49. return
  50. }
  51. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  52. return
  53. }
  54. var newBranches []string
  55. for _, br := range request.GitRepoBranches {
  56. name := strings.TrimSpace(br)
  57. if len(name) > 0 {
  58. newBranches = append(newBranches, name)
  59. }
  60. }
  61. changed := !reflect.DeepEqual(env.ToEnvironmentType().GitRepoBranches, newBranches)
  62. if changed {
  63. env.GitRepoBranches = strings.Join(request.GitRepoBranches, ",")
  64. }
  65. newBranches = []string{}
  66. for _, br := range request.GitDeployBranches {
  67. name := strings.TrimSpace(br)
  68. if len(name) > 0 {
  69. newBranches = append(newBranches, name)
  70. }
  71. }
  72. changed = !reflect.DeepEqual(env.ToEnvironmentType().GitDeployBranches, newBranches)
  73. if changed {
  74. // let us check if the webhook has access to the "push" event
  75. client, err := getGithubClientFromEnvironment(c.Config(), env)
  76. if err != nil {
  77. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  78. return
  79. }
  80. hook, _, err := client.Repositories.GetHook(
  81. context.Background(), env.GitRepoOwner, env.GitRepoName, env.GithubWebhookID,
  82. )
  83. if err != nil {
  84. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  85. return
  86. }
  87. found := false
  88. for _, ev := range hook.Events {
  89. if ev == "push" {
  90. found = true
  91. break
  92. }
  93. }
  94. if !found {
  95. hook.Events = append(hook.Events, "push")
  96. _, _, err := client.Repositories.EditHook(
  97. context.Background(), env.GitRepoOwner, env.GitRepoName, env.GithubWebhookID, hook,
  98. )
  99. if err != nil {
  100. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  101. return
  102. }
  103. }
  104. env.GitDeployBranches = strings.Join(request.GitDeployBranches, ",")
  105. if len(request.GitDeployBranches) > 0 && c.Config().ServerConf.EnableAutoPreviewBranchDeploy {
  106. errs := autoDeployBranch(env, c.Config(), request.GitDeployBranches, true)
  107. if len(errs) > 0 {
  108. errString := errs[0].Error()
  109. for _, e := range errs {
  110. errString += ": " + e.Error()
  111. }
  112. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  113. fmt.Errorf("error auto deploying preview branches: %s", errString), http.StatusConflict),
  114. )
  115. return
  116. }
  117. }
  118. }
  119. if request.DisableNewComments != env.NewCommentsDisabled {
  120. env.NewCommentsDisabled = request.DisableNewComments
  121. changed = true
  122. }
  123. if request.Mode != env.Mode {
  124. env.Mode = request.Mode
  125. changed = true
  126. }
  127. if len(request.NamespaceLabels) > 0 {
  128. var labels []string
  129. for k, v := range request.NamespaceLabels {
  130. labels = append(labels, fmt.Sprintf("%s=%s", k, v))
  131. }
  132. env.NamespaceLabels = []byte(strings.Join(labels, ","))
  133. changed = true
  134. } else {
  135. env.NamespaceLabels = []byte{}
  136. changed = true
  137. }
  138. if changed {
  139. env, err = c.Repo().Environment().UpdateEnvironment(env)
  140. if err != nil {
  141. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  142. return
  143. }
  144. }
  145. c.WriteResult(w, r, env.ToEnvironmentType())
  146. }