app_metrics.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package porter_app
  2. import (
  3. "net/http"
  4. "github.com/porter-dev/porter/internal/deployment_target"
  5. "github.com/porter-dev/porter/internal/kubernetes/prometheus"
  6. "github.com/porter-dev/porter/internal/telemetry"
  7. "github.com/porter-dev/porter/api/server/authz"
  8. "github.com/porter-dev/porter/api/server/handlers"
  9. "github.com/porter-dev/porter/api/server/shared"
  10. "github.com/porter-dev/porter/api/server/shared/apierrors"
  11. "github.com/porter-dev/porter/api/server/shared/config"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/models"
  14. )
  15. // AppMetricsHandler handles the /apps/metrics endpoint
  16. type AppMetricsHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. authz.KubernetesAgentGetter
  19. }
  20. // NewAppMetricsHandler returns a new AppMetricsHandler
  21. func NewAppMetricsHandler(
  22. config *config.Config,
  23. decoderValidator shared.RequestDecoderValidator,
  24. writer shared.ResultWriter,
  25. ) *AppMetricsHandler {
  26. return &AppMetricsHandler{
  27. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  28. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  29. }
  30. }
  31. // MetricsRequest is the expected request body for the /apps/metrics endpoint
  32. type MetricsRequest struct {
  33. // Deployment target of the app to query for metrics
  34. DeploymentTargetID string `schema:"deployment_target_id"`
  35. // Below is just a copy of prometheus.QueryOpts, other than namespace
  36. // the name of the metric being queried for
  37. Metric string `schema:"metric"`
  38. ShouldSum bool `schema:"shouldsum"`
  39. Kind string `schema:"kind"`
  40. PodList []string `schema:"pods"`
  41. Name string `schema:"name"`
  42. // start time (in unix timestamp) for prometheus results
  43. StartRange uint `schema:"startrange"`
  44. // end time time (in unix timestamp) for prometheus results
  45. EndRange uint `schema:"endrange"`
  46. Resolution string `schema:"resolution"`
  47. Percentile float64 `schema:"percentile"`
  48. }
  49. // ServeHTTP returns metrics for a given app in the provided deployment target
  50. func (c *AppMetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  51. ctx, span := telemetry.NewSpan(r.Context(), "serve-app-metrics")
  52. defer span.End()
  53. r = r.Clone(ctx)
  54. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  55. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  56. request := &MetricsRequest{}
  57. if ok := c.DecodeAndValidate(w, r, request); !ok {
  58. err := telemetry.Error(ctx, span, nil, "error decoding request")
  59. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  60. return
  61. }
  62. if request.DeploymentTargetID == "" {
  63. err := telemetry.Error(ctx, span, nil, "must provide deployment target id")
  64. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  65. return
  66. }
  67. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "deployment-target-id", Value: request.DeploymentTargetID})
  68. deploymentTarget, err := deployment_target.DeploymentTargetDetails(ctx, deployment_target.DeploymentTargetDetailsInput{
  69. ProjectID: int64(project.ID),
  70. ClusterID: int64(cluster.ID),
  71. DeploymentTargetID: request.DeploymentTargetID,
  72. CCPClient: c.Config().ClusterControlPlaneClient,
  73. })
  74. if err != nil {
  75. err := telemetry.Error(ctx, span, err, "error getting deployment target details")
  76. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  77. return
  78. }
  79. namespace := deploymentTarget.Namespace
  80. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "namespace", Value: namespace})
  81. agent, err := c.GetAgent(r, cluster, "")
  82. if err != nil {
  83. err = telemetry.Error(ctx, span, err, "error getting k8s agent")
  84. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  85. return
  86. }
  87. // get prometheus service
  88. promSvc, found, err := prometheus.GetPrometheusService(agent.Clientset)
  89. if err != nil || !found {
  90. err = telemetry.Error(ctx, span, err, "error getting prometheus service")
  91. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  92. return
  93. }
  94. telemetry.WithAttributes(span,
  95. telemetry.AttributeKV{Key: "metric", Value: request.Metric},
  96. telemetry.AttributeKV{Key: "shouldsum", Value: request.ShouldSum},
  97. telemetry.AttributeKV{Key: "kind", Value: request.Kind},
  98. telemetry.AttributeKV{Key: "name", Value: request.Name},
  99. telemetry.AttributeKV{Key: "start-range", Value: request.StartRange},
  100. telemetry.AttributeKV{Key: "end-range", Value: request.EndRange},
  101. telemetry.AttributeKV{Key: "resolution", Value: request.Resolution},
  102. telemetry.AttributeKV{Key: "percentile", Value: request.Percentile},
  103. )
  104. queryOpts := &prometheus.QueryOpts{
  105. Metric: request.Metric,
  106. ShouldSum: request.ShouldSum,
  107. Kind: request.Kind,
  108. Name: request.Name,
  109. Namespace: namespace,
  110. StartRange: request.StartRange,
  111. EndRange: request.EndRange,
  112. Resolution: request.Resolution,
  113. Percentile: request.Percentile,
  114. }
  115. rawQuery, err := prometheus.QueryPrometheus(ctx, agent.Clientset, promSvc, queryOpts)
  116. if err != nil {
  117. err = telemetry.Error(ctx, span, err, "error querying prometheus")
  118. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  119. return
  120. }
  121. c.WriteResult(w, r, rawQuery)
  122. }