helm_release.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. namespace := fmt.Sprintf("app-%s", appName)
  62. helmAgent, err := c.GetHelmAgent(ctx, r, cluster, namespace)
  63. if err != nil {
  64. err = telemetry.Error(ctx, span, err, "error getting helm agent")
  65. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  66. return
  67. }
  68. rel, err := helmAgent.GetRelease(ctx, appName, int(version), false)
  69. if err != nil {
  70. err = telemetry.Error(ctx, span, err, "error getting helm release")
  71. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  72. return
  73. }
  74. if rel == nil {
  75. err = telemetry.Error(ctx, span, nil, "release is nil")
  76. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  77. return
  78. }
  79. config := rel.Config
  80. tag, err := imageTagFromConfig(config)
  81. if err != nil {
  82. err := telemetry.Error(ctx, span, err, "error getting image tag from config")
  83. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  84. return
  85. }
  86. revisionId, err := appRevisionIdFromConfig(config)
  87. if err != nil {
  88. err := telemetry.Error(ctx, span, err, "error getting app revision id from config")
  89. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  90. return
  91. }
  92. revision, err := c.Repo().AppRevision().AppRevisionById(project.ID, revisionId)
  93. if err != nil {
  94. err := telemetry.Error(ctx, span, err, "error getting app revision by instance id and revision number")
  95. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  96. return
  97. }
  98. if revision == nil {
  99. err := telemetry.Error(ctx, span, err, "app revision is nil")
  100. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  101. return
  102. }
  103. res := &types.Release{
  104. Release: &release.Release{
  105. Name: "",
  106. Info: nil,
  107. Chart: nil,
  108. Config: map[string]interface{}{
  109. "global": map[string]interface{}{
  110. "image": map[string]interface{}{
  111. "tag": tag,
  112. },
  113. },
  114. },
  115. Manifest: "",
  116. Hooks: nil,
  117. Version: rel.Version,
  118. Namespace: "",
  119. Labels: nil,
  120. },
  121. PorterVersion: uint(revision.RevisionNumber),
  122. AppRevisionId: revisionId,
  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. }
  225. func imageTagFromConfig(config map[string]interface{}) (string, error) {
  226. globalConfig, ok := config["global"].(map[string]interface{})
  227. if !ok || globalConfig == nil {
  228. return "", fmt.Errorf("error converting global config to map")
  229. }
  230. imageConfig, ok := globalConfig["image"].(map[string]interface{})
  231. if !ok || imageConfig == nil {
  232. return "", fmt.Errorf("error converting image config to map")
  233. }
  234. tag, ok := imageConfig["tag"].(string)
  235. if !ok || tag == "" {
  236. return "", fmt.Errorf("error converting tag to string")
  237. }
  238. return tag, nil
  239. }
  240. func appRevisionIdFromConfig(config map[string]interface{}) (string, error) {
  241. var appRevisionId string
  242. for _, val := range config {
  243. if val == nil {
  244. continue
  245. }
  246. m, ok := val.(map[string]interface{})
  247. if !ok || m == nil {
  248. continue
  249. }
  250. labels, ok := m["labels"].(map[string]interface{})
  251. if !ok || labels == nil {
  252. continue
  253. }
  254. id, ok := labels["porter.run/app-revision-id"].(string)
  255. if !ok || id == "" {
  256. continue
  257. }
  258. appRevisionId = id
  259. break
  260. }
  261. if appRevisionId == "" {
  262. return "", fmt.Errorf("app revision id not found in config")
  263. }
  264. return appRevisionId, nil
  265. }