list.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package environment_groups
  2. import (
  3. "net/http"
  4. "strings"
  5. "time"
  6. "connectrpc.com/connect"
  7. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  8. "github.com/porter-dev/porter/api/server/authz"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. "github.com/porter-dev/porter/api/server/shared/config"
  13. "github.com/porter-dev/porter/api/types"
  14. environmentgroups "github.com/porter-dev/porter/internal/kubernetes/environment_groups"
  15. "github.com/porter-dev/porter/internal/models"
  16. "github.com/porter-dev/porter/internal/telemetry"
  17. )
  18. type ListEnvironmentGroupsHandler struct {
  19. handlers.PorterHandlerReadWriter
  20. authz.KubernetesAgentGetter
  21. }
  22. func NewListEnvironmentGroupsHandler(
  23. config *config.Config,
  24. decoderValidator shared.RequestDecoderValidator,
  25. writer shared.ResultWriter,
  26. ) *ListEnvironmentGroupsHandler {
  27. return &ListEnvironmentGroupsHandler{
  28. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  29. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  30. }
  31. }
  32. // ListEnvironmentGroupsRequest is the request object for the /environment-groups endpoint
  33. type ListEnvironmentGroupsRequest struct {
  34. // Type of the env group to filter by. If empty, all env groups will be returned.
  35. Type string `json:"type"`
  36. }
  37. type ListEnvironmentGroupsResponse struct {
  38. EnvironmentGroups []EnvironmentGroupListItem `json:"environment_groups,omitempty"`
  39. }
  40. type EnvironmentGroupListItem struct {
  41. Name string `json:"name"`
  42. Type string `json:"type"`
  43. LatestVersion int `json:"latest_version"`
  44. Variables map[string]string `json:"variables,omitempty"`
  45. SecretVariables map[string]string `json:"secret_variables,omitempty"`
  46. CreatedAtUTC time.Time `json:"created_at"`
  47. LinkedApplications []string `json:"linked_applications,omitempty"`
  48. }
  49. func (c *ListEnvironmentGroupsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  50. ctx, span := telemetry.NewSpan(r.Context(), "serve-list-env-groups")
  51. defer span.End()
  52. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  53. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  54. request := &ListEnvironmentGroupsRequest{}
  55. if ok := c.DecodeAndValidate(w, r, request); !ok {
  56. err := telemetry.Error(ctx, span, nil, "unable to decode or validate request body")
  57. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  58. return
  59. }
  60. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "env-group-type", Value: request.Type})
  61. agent, err := c.GetAgent(r, cluster, "")
  62. if err != nil {
  63. err = telemetry.Error(ctx, span, err, "unable to connect to cluster")
  64. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusServiceUnavailable))
  65. return
  66. }
  67. allEnvGroupVersions, err := environmentgroups.ListEnvironmentGroups(ctx, agent, environmentgroups.WithNamespace(environmentgroups.Namespace_EnvironmentGroups), environmentgroups.WithoutDefaultAppEnvironmentGroups(), environmentgroups.WithoutDefaultAddonEnvironmentGroups())
  68. if err != nil {
  69. err = telemetry.Error(ctx, span, err, "unable to list all environment groups")
  70. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  71. return
  72. }
  73. if request.Type != "" {
  74. var filteredEnvGroupVersions []environmentgroups.EnvironmentGroup
  75. for _, envGroup := range allEnvGroupVersions {
  76. if envGroup.Type == request.Type {
  77. filteredEnvGroupVersions = append(filteredEnvGroupVersions, envGroup)
  78. }
  79. }
  80. allEnvGroupVersions = filteredEnvGroupVersions
  81. }
  82. envGroupSet := make(map[string]struct{})
  83. for _, envGroup := range allEnvGroupVersions {
  84. if envGroup.Name == "" {
  85. continue
  86. }
  87. if _, ok := envGroupSet[envGroup.Name]; !ok {
  88. envGroupSet[envGroup.Name] = struct{}{}
  89. }
  90. }
  91. var envGroups []EnvironmentGroupListItem
  92. for envGroupName := range envGroupSet {
  93. latestVersion, err := environmentgroups.LatestBaseEnvironmentGroup(ctx, agent, envGroupName)
  94. if err != nil {
  95. err = telemetry.Error(ctx, span, err, "unable to get latest environment groups")
  96. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  97. return
  98. }
  99. var linkedApplications []string
  100. if !project.GetFeatureFlag(models.ValidateApplyV2, c.Config().LaunchDarklyClient) {
  101. applications, err := environmentgroups.LinkedApplications(ctx, agent, latestVersion.Name, true)
  102. if err != nil {
  103. err = telemetry.Error(ctx, span, err, "unable to get linked applications")
  104. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  105. return
  106. }
  107. applicationSetForEnvGroup := make(map[string]struct{})
  108. for _, app := range applications {
  109. if app.Namespace == "" {
  110. continue
  111. }
  112. if _, ok := applicationSetForEnvGroup[app.Namespace]; !ok {
  113. applicationSetForEnvGroup[app.Namespace] = struct{}{}
  114. }
  115. }
  116. for appNamespace := range applicationSetForEnvGroup {
  117. porterAppName := strings.TrimPrefix(appNamespace, "porter-stack-")
  118. linkedApplications = append(linkedApplications, porterAppName)
  119. }
  120. } else {
  121. appsLinkedToEnvGroupReq := connect.NewRequest(&porterv1.AppsLinkedToEnvGroupRequest{
  122. ProjectId: int64(project.ID),
  123. ClusterId: int64(cluster.ID),
  124. EnvGroupName: envGroupName,
  125. IgnorePreview: true,
  126. })
  127. appsLinkedToEnvGroupResp, err := c.Config().ClusterControlPlaneClient.AppsLinkedToEnvGroup(ctx, appsLinkedToEnvGroupReq)
  128. if err != nil {
  129. err = telemetry.Error(ctx, span, err, "unable to get linked applications")
  130. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  131. return
  132. }
  133. if appsLinkedToEnvGroupResp == nil || appsLinkedToEnvGroupResp.Msg == nil {
  134. err = telemetry.Error(ctx, span, err, "ccp resp is nil")
  135. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  136. return
  137. }
  138. for _, app := range appsLinkedToEnvGroupResp.Msg.LinkedApps {
  139. if app != nil {
  140. linkedApplications = append(linkedApplications, app.Name)
  141. }
  142. }
  143. }
  144. secrets := make(map[string]string)
  145. for k, v := range latestVersion.SecretVariables {
  146. secrets[k] = string(v)
  147. }
  148. envGroups = append(envGroups, EnvironmentGroupListItem{
  149. Name: latestVersion.Name,
  150. Type: latestVersion.Type,
  151. LatestVersion: latestVersion.Version,
  152. Variables: latestVersion.Variables,
  153. SecretVariables: secrets,
  154. CreatedAtUTC: latestVersion.CreatedAtUTC,
  155. LinkedApplications: linkedApplications,
  156. })
  157. }
  158. c.WriteResult(w, r, ListEnvironmentGroupsResponse{EnvironmentGroups: envGroups})
  159. }