helm_release.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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): delete these database calls once endpoint is deprecated
  73. var revision *models.AppRevision
  74. // treat version 0 as latest like helm
  75. if version == 0 {
  76. revision, err = c.Repo().AppRevision().LatestNumberedAppRevision(project.ID, appInstance.Id)
  77. if err != nil {
  78. err := telemetry.Error(ctx, span, err, "error getting latest numbered app revision")
  79. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  80. return
  81. }
  82. } else {
  83. revision, err = c.Repo().AppRevision().AppRevisionByInstanceIDAndRevisionNumber(project.ID, appInstance.Id, version)
  84. if err != nil {
  85. err := telemetry.Error(ctx, span, err, "error getting app revision by instance id and revision number")
  86. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  87. return
  88. }
  89. }
  90. if revision == nil {
  91. err := telemetry.Error(ctx, span, err, "app revision is nil")
  92. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  93. return
  94. }
  95. appRevisionRequest := connect.NewRequest(&porterv1.GetAppRevisionRequest{
  96. ProjectId: int64(project.ID),
  97. AppRevisionId: revision.ID.String(),
  98. })
  99. getAppRevisionResp, err := c.Config().ClusterControlPlaneClient.GetAppRevision(ctx, appRevisionRequest)
  100. if err != nil {
  101. err := telemetry.Error(ctx, span, err, "error getting current app revision from cluster control plane client")
  102. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  103. return
  104. }
  105. if getAppRevisionResp.Msg == nil || getAppRevisionResp.Msg.AppRevision == nil {
  106. err := telemetry.Error(ctx, span, err, "app revision is nil")
  107. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  108. return
  109. }
  110. appRevision := getAppRevisionResp.Msg.AppRevision
  111. if appRevision.App == nil || appRevision.App.Image == nil {
  112. err := telemetry.Error(ctx, span, err, "app revision app or image is nil")
  113. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  114. return
  115. }
  116. res := &types.Release{
  117. Release: &release.Release{
  118. Name: "",
  119. Info: nil,
  120. Chart: nil,
  121. Config: map[string]interface{}{
  122. "global": map[string]interface{}{
  123. "image": map[string]interface{}{
  124. "tag": appRevision.App.Image.Tag,
  125. },
  126. },
  127. },
  128. Manifest: "",
  129. Hooks: nil,
  130. Version: int(appRevision.RevisionNumber),
  131. Namespace: "",
  132. Labels: nil,
  133. },
  134. PorterRelease: nil,
  135. Form: nil,
  136. }
  137. c.WriteResult(w, r, res)
  138. return
  139. }
  140. namespace := utils.NamespaceFromPorterAppName(appName)
  141. helmAgent, err := c.GetHelmAgent(ctx, r, cluster, namespace)
  142. if err != nil {
  143. err = telemetry.Error(ctx, span, err, "error getting helm agent")
  144. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  145. return
  146. }
  147. release, err := helmAgent.GetRelease(ctx, appName, int(version), false)
  148. if err != nil {
  149. err = telemetry.Error(ctx, span, err, "error getting helm release")
  150. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  151. return
  152. }
  153. res := &types.Release{
  154. Release: release,
  155. }
  156. c.WriteResult(w, r, res)
  157. }
  158. type appInstanceFromAppNameInput struct {
  159. ProjectID uint
  160. ClusterID uint
  161. AppName string
  162. CCPClient porterv1connect.ClusterControlPlaneServiceClient
  163. }
  164. // appInstanceFromAppName makes a best-effort attempt to find the app instance for an app name
  165. // It does this by getting all deployment targets in the cluster, then getting all app instances in the project,
  166. // then filtering the app instances by app name and non-preview deployment targets. If there is only one matching
  167. // app instance, then the instance is returned. Otherwise, an error is returned.
  168. func appInstanceFromAppName(ctx context.Context, input appInstanceFromAppNameInput) (*porterv1.AppInstance, error) {
  169. ctx, span := telemetry.NewSpan(ctx, "app-instance-from-app-name")
  170. defer span.End()
  171. var appInstance *porterv1.AppInstance
  172. telemetry.WithAttributes(span,
  173. telemetry.AttributeKV{Key: "project-id", Value: input.ProjectID},
  174. telemetry.AttributeKV{Key: "cluster-id", Value: input.ClusterID},
  175. telemetry.AttributeKV{Key: "app-name", Value: input.AppName},
  176. )
  177. listDeploymentTargetsReq := connect.NewRequest(&porterv1.DeploymentTargetsRequest{
  178. ProjectId: int64(input.ProjectID),
  179. ClusterId: int64(input.ClusterID),
  180. })
  181. listDeploymentTargetsResp, err := input.CCPClient.DeploymentTargets(ctx, listDeploymentTargetsReq)
  182. if err != nil {
  183. return appInstance, telemetry.Error(ctx, span, err, "error getting deployment targets from cluster control plane client")
  184. }
  185. if listDeploymentTargetsResp.Msg == nil || listDeploymentTargetsResp.Msg.DeploymentTargets == nil {
  186. return appInstance, telemetry.Error(ctx, span, nil, "deployment targets response is nil")
  187. }
  188. deploymentTargetSet := map[string]*porterv1.DeploymentTarget{}
  189. for _, deploymentTarget := range listDeploymentTargetsResp.Msg.DeploymentTargets {
  190. deploymentTargetSet[deploymentTarget.Id] = deploymentTarget
  191. }
  192. listAppInstancesReq := connect.NewRequest(&porterv1.ListAppInstancesRequest{
  193. ProjectId: int64(input.ProjectID),
  194. })
  195. listAppInstancesResp, err := input.CCPClient.ListAppInstances(ctx, listAppInstancesReq)
  196. if err != nil {
  197. return appInstance, telemetry.Error(ctx, span, err, "error getting app instances from cluster control plane client")
  198. }
  199. if listAppInstancesResp.Msg == nil || listAppInstancesResp.Msg.AppInstances == nil {
  200. return appInstance, telemetry.Error(ctx, span, nil, "app instances response is nil")
  201. }
  202. var matchingAppInstances []*porterv1.AppInstance
  203. for _, instance := range listAppInstancesResp.Msg.AppInstances {
  204. if instance == nil {
  205. continue
  206. }
  207. if instance.Name == input.AppName {
  208. if deploymentTargetSet[instance.DeploymentTargetId] == nil {
  209. continue
  210. }
  211. if deploymentTargetSet[instance.DeploymentTargetId].IsPreview {
  212. continue
  213. }
  214. matchingAppInstances = append(matchingAppInstances, instance)
  215. }
  216. }
  217. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "len-app-instances", Value: len(matchingAppInstances)})
  218. printInstances := func([]*porterv1.AppInstance) string {
  219. var stringInstances []string
  220. for _, appInstance := range matchingAppInstances {
  221. stringInstances = append(stringInstances, appInstance.String())
  222. }
  223. return fmt.Sprintf("[%s]", strings.Join(stringInstances, ","))
  224. }
  225. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-instances", Value: printInstances(matchingAppInstances)})
  226. if len(matchingAppInstances) == 0 {
  227. return appInstance, telemetry.Error(ctx, span, nil, "no matching app instances found")
  228. }
  229. if len(matchingAppInstances) > 1 {
  230. return appInstance, telemetry.Error(ctx, span, nil, "multiple matching app instances found")
  231. }
  232. matchingDeploymentTarget := deploymentTargetSet[matchingAppInstances[0].DeploymentTargetId]
  233. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "matching-deployment-target", Value: matchingDeploymentTarget.String()})
  234. return matchingAppInstances[0], nil
  235. }