helm_release.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package porter_app
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/porter-dev/api-contracts/generated/go/porter/v1/porterv1connect"
  8. "github.com/stefanmcshane/helm/pkg/release"
  9. "connectrpc.com/connect"
  10. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  11. "github.com/porter-dev/porter/api/server/authz"
  12. "github.com/porter-dev/porter/api/server/handlers"
  13. "github.com/porter-dev/porter/api/server/shared"
  14. "github.com/porter-dev/porter/api/server/shared/apierrors"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/api/server/shared/requestutils"
  17. "github.com/porter-dev/porter/api/types"
  18. utils "github.com/porter-dev/porter/api/utils/porter_app"
  19. "github.com/porter-dev/porter/internal/models"
  20. "github.com/porter-dev/porter/internal/telemetry"
  21. )
  22. type PorterAppHelmReleaseGetHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. authz.KubernetesAgentGetter
  25. }
  26. func NewPorterAppHelmReleaseGetHandler(
  27. config *config.Config,
  28. writer shared.ResultWriter,
  29. ) *PorterAppHelmReleaseGetHandler {
  30. return &PorterAppHelmReleaseGetHandler{
  31. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, nil, writer),
  32. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  33. }
  34. }
  35. func (c *PorterAppHelmReleaseGetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  36. ctx := r.Context()
  37. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  38. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  39. ctx, span := telemetry.NewSpan(ctx, "serve-get-porter-app-helm-release")
  40. defer span.End()
  41. telemetry.WithAttributes(span,
  42. telemetry.AttributeKV{Key: "project-id", Value: project.ID},
  43. telemetry.AttributeKV{Key: "cluster-id", Value: cluster.ID},
  44. )
  45. appName, reqErr := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
  46. if reqErr != nil {
  47. err := telemetry.Error(ctx, span, reqErr, "error getting stack name from url")
  48. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  49. return
  50. }
  51. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-name", Value: appName})
  52. version, reqErr := requestutils.GetURLParamUint(r, types.URLParamReleaseVersion)
  53. if reqErr != nil {
  54. err := telemetry.Error(ctx, span, reqErr, "error getting version from url")
  55. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  56. return
  57. }
  58. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "version", Value: version})
  59. // TODO (POR-2170): Deprecate this entire endpoint in favor of v2 endpoints
  60. if project.GetFeatureFlag(models.ValidateApplyV2, c.Config().LaunchDarklyClient) {
  61. appInstance, err := appInstanceFromAppName(ctx, appInstanceFromAppNameInput{
  62. ProjectID: project.ID,
  63. ClusterID: cluster.ID,
  64. AppName: appName,
  65. CCPClient: c.Config().ClusterControlPlaneClient,
  66. })
  67. if err != nil {
  68. err := telemetry.Error(ctx, span, err, "error getting deployment target id from app name")
  69. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  70. return
  71. }
  72. // TODO (POR-2170): remove this database call once endpoint is deprecated
  73. revision, err := c.Repo().AppRevision().AppRevisionByInstanceIDAndRevisionNumber(project.ID, appInstance.Id, version)
  74. if err != nil {
  75. err := telemetry.Error(ctx, span, err, "error getting app revision by instance id and revision number")
  76. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  77. return
  78. }
  79. if revision == nil {
  80. err := telemetry.Error(ctx, span, err, "app revision is nil")
  81. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  82. return
  83. }
  84. appRevisionRequest := connect.NewRequest(&porterv1.GetAppRevisionRequest{
  85. ProjectId: int64(project.ID),
  86. AppRevisionId: revision.ID.String(),
  87. })
  88. getAppRevisionResp, err := c.Config().ClusterControlPlaneClient.GetAppRevision(ctx, appRevisionRequest)
  89. if err != nil {
  90. err := telemetry.Error(ctx, span, err, "error getting current app revision from cluster control plane client")
  91. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  92. return
  93. }
  94. if getAppRevisionResp.Msg == nil || getAppRevisionResp.Msg.AppRevision == nil {
  95. err := telemetry.Error(ctx, span, err, "app revision is nil")
  96. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  97. return
  98. }
  99. appRevision := getAppRevisionResp.Msg.AppRevision
  100. if appRevision.App == nil || appRevision.App.Image == nil {
  101. err := telemetry.Error(ctx, span, err, "app revision app or image is nil")
  102. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  103. return
  104. }
  105. res := &types.Release{
  106. Release: &release.Release{
  107. Name: "",
  108. Info: nil,
  109. Chart: nil,
  110. Config: map[string]interface{}{
  111. "global": map[string]interface{}{
  112. "image": map[string]interface{}{
  113. "tag": appRevision.App.Image.Tag,
  114. },
  115. },
  116. },
  117. Manifest: "",
  118. Hooks: nil,
  119. Version: int(appRevision.RevisionNumber),
  120. Namespace: "",
  121. Labels: nil,
  122. },
  123. PorterRelease: nil,
  124. Form: nil,
  125. }
  126. c.WriteResult(w, r, res)
  127. return
  128. }
  129. namespace := utils.NamespaceFromPorterAppName(appName)
  130. helmAgent, err := c.GetHelmAgent(ctx, r, cluster, namespace)
  131. if err != nil {
  132. err = telemetry.Error(ctx, span, err, "error getting helm agent")
  133. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  134. return
  135. }
  136. release, err := helmAgent.GetRelease(ctx, appName, int(version), false)
  137. if err != nil {
  138. err = telemetry.Error(ctx, span, err, "error getting helm release")
  139. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  140. return
  141. }
  142. res := &types.Release{
  143. Release: release,
  144. }
  145. c.WriteResult(w, r, res)
  146. }
  147. type appInstanceFromAppNameInput struct {
  148. ProjectID uint
  149. ClusterID uint
  150. AppName string
  151. CCPClient porterv1connect.ClusterControlPlaneServiceClient
  152. }
  153. // appInstanceFromAppName makes a best-effort attempt to find the app instance for an app name
  154. // It does this by getting all deployment targets in the cluster, then getting all app instances in the project,
  155. // then filtering the app instances by app name and non-preview deployment targets. If there is only one matching
  156. // app instance, then the instance is returned. Otherwise, an error is returned.
  157. func appInstanceFromAppName(ctx context.Context, input appInstanceFromAppNameInput) (*porterv1.AppInstance, error) {
  158. ctx, span := telemetry.NewSpan(ctx, "app-instance-from-app-name")
  159. defer span.End()
  160. var appInstance *porterv1.AppInstance
  161. telemetry.WithAttributes(span,
  162. telemetry.AttributeKV{Key: "project-id", Value: input.ProjectID},
  163. telemetry.AttributeKV{Key: "cluster-id", Value: input.ClusterID},
  164. telemetry.AttributeKV{Key: "app-name", Value: input.AppName},
  165. )
  166. listDeploymentTargetsReq := connect.NewRequest(&porterv1.DeploymentTargetsRequest{
  167. ProjectId: int64(input.ProjectID),
  168. ClusterId: int64(input.ClusterID),
  169. })
  170. listDeploymentTargetsResp, err := input.CCPClient.DeploymentTargets(ctx, listDeploymentTargetsReq)
  171. if err != nil {
  172. return appInstance, telemetry.Error(ctx, span, err, "error getting deployment targets from cluster control plane client")
  173. }
  174. if listDeploymentTargetsResp.Msg == nil || listDeploymentTargetsResp.Msg.DeploymentTargets == nil {
  175. return appInstance, telemetry.Error(ctx, span, nil, "deployment targets response is nil")
  176. }
  177. deploymentTargetSet := map[string]*porterv1.DeploymentTarget{}
  178. for _, deploymentTarget := range listDeploymentTargetsResp.Msg.DeploymentTargets {
  179. deploymentTargetSet[deploymentTarget.Id] = deploymentTarget
  180. }
  181. listAppInstancesReq := connect.NewRequest(&porterv1.ListAppInstancesRequest{
  182. ProjectId: int64(input.ProjectID),
  183. })
  184. listAppInstancesResp, err := input.CCPClient.ListAppInstances(ctx, listAppInstancesReq)
  185. if err != nil {
  186. return appInstance, telemetry.Error(ctx, span, err, "error getting app instances from cluster control plane client")
  187. }
  188. if listAppInstancesResp.Msg == nil || listAppInstancesResp.Msg.AppInstances == nil {
  189. return appInstance, telemetry.Error(ctx, span, nil, "app instances response is nil")
  190. }
  191. var matchingAppInstances []*porterv1.AppInstance
  192. for _, instance := range listAppInstancesResp.Msg.AppInstances {
  193. if instance == nil {
  194. continue
  195. }
  196. if instance.Name == input.AppName {
  197. if deploymentTargetSet[instance.DeploymentTargetId] == nil {
  198. continue
  199. }
  200. if deploymentTargetSet[instance.DeploymentTargetId].IsPreview {
  201. continue
  202. }
  203. matchingAppInstances = append(matchingAppInstances, instance)
  204. }
  205. }
  206. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "len-app-instances", Value: len(matchingAppInstances)})
  207. printInstances := func([]*porterv1.AppInstance) string {
  208. var stringInstances []string
  209. for _, appInstance := range matchingAppInstances {
  210. stringInstances = append(stringInstances, appInstance.String())
  211. }
  212. return fmt.Sprintf("[%s]", strings.Join(stringInstances, ","))
  213. }
  214. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-instances", Value: printInstances(matchingAppInstances)})
  215. if len(matchingAppInstances) == 0 {
  216. return appInstance, telemetry.Error(ctx, span, nil, "no matching app instances found")
  217. }
  218. if len(matchingAppInstances) > 1 {
  219. return appInstance, telemetry.Error(ctx, span, nil, "multiple matching app instances found")
  220. }
  221. matchingDeploymentTarget := deploymentTargetSet[matchingAppInstances[0].DeploymentTargetId]
  222. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "matching-deployment-target", Value: matchingDeploymentTarget.String()})
  223. return matchingAppInstances[0], nil
  224. }