logs_apply_v2.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package porter_app
  2. import (
  3. "fmt"
  4. "net/http"
  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/server/shared/requestutils"
  14. "github.com/porter-dev/porter/api/types"
  15. porter_agent "github.com/porter-dev/porter/internal/kubernetes/porter_agent/v2"
  16. "github.com/porter-dev/porter/internal/models"
  17. "github.com/porter-dev/porter/internal/telemetry"
  18. )
  19. // AppLogsHandler handles the /apps/logs endpoint
  20. type AppLogsHandler struct {
  21. handlers.PorterHandlerReadWriter
  22. authz.KubernetesAgentGetter
  23. }
  24. // NewAppLogsHandler returns a new AppLogsHandler
  25. func NewAppLogsHandler(
  26. config *config.Config,
  27. decoderValidator shared.RequestDecoderValidator,
  28. writer shared.ResultWriter,
  29. ) *AppLogsHandler {
  30. return &AppLogsHandler{
  31. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  32. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  33. }
  34. }
  35. // AppLogsRequest represents the accepted fields on a request to the /apps/logs endpoint
  36. type AppLogsRequest struct {
  37. DeploymentTargetID string `schema:"deployment_target_id"`
  38. ServiceName string `schema:"service_name"`
  39. AppID uint `schema:"app_id"`
  40. Limit uint `schema:"limit"`
  41. StartRange time.Time `schema:"start_range,omitempty"`
  42. EndRange time.Time `schema:"end_range,omitempty"`
  43. SearchParam string `schema:"search_param"`
  44. Direction string `schema:"direction"`
  45. AppRevisionID string `schema:"app_revision_id"`
  46. }
  47. const (
  48. lokiLabel_PorterAppName = "porter_run_app_name"
  49. lokiLabel_PorterAppID = "porter_run_app_id"
  50. lokiLabel_PorterServiceName = "porter_run_service_name"
  51. lokiLabel_PorterAppRevisionID = "porter_run_app_revision_id"
  52. lokiLabel_DeploymentTargetId = "porter_run_deployment_target_id"
  53. lokiLabel_Namespace = "namespace"
  54. )
  55. // ServeHTTP gets logs for a given app, service, and deployment target
  56. func (c *AppLogsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  57. ctx, span := telemetry.NewSpan(r.Context(), "serve-app-logs")
  58. defer span.End()
  59. r = r.Clone(ctx)
  60. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  61. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  62. request := &AppLogsRequest{}
  63. if ok := c.DecodeAndValidate(w, r, request); !ok {
  64. err := telemetry.Error(ctx, span, nil, "invalid request")
  65. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  66. return
  67. }
  68. appName, reqErr := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
  69. if reqErr != nil {
  70. err := telemetry.Error(ctx, span, reqErr, "porter app name not found in request")
  71. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  72. return
  73. }
  74. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-name", Value: appName})
  75. if request.AppID == 0 {
  76. err := telemetry.Error(ctx, span, nil, "must provide app id")
  77. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  78. return
  79. }
  80. if request.ServiceName == "" {
  81. err := telemetry.Error(ctx, span, nil, "must provide service name")
  82. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  83. return
  84. }
  85. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "service-name", Value: request.ServiceName})
  86. if request.DeploymentTargetID == "" {
  87. err := telemetry.Error(ctx, span, nil, "must provide deployment target id")
  88. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  89. return
  90. }
  91. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "deployment-target-id", Value: request.DeploymentTargetID})
  92. deploymentTargetDetailsReq := connect.NewRequest(&porterv1.DeploymentTargetDetailsRequest{
  93. ProjectId: int64(project.ID),
  94. DeploymentTargetId: request.DeploymentTargetID,
  95. })
  96. deploymentTargetDetailsResp, err := c.Config().ClusterControlPlaneClient.DeploymentTargetDetails(ctx, deploymentTargetDetailsReq)
  97. if err != nil {
  98. err := telemetry.Error(ctx, span, err, "error getting deployment target details from cluster control plane client")
  99. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  100. return
  101. }
  102. if deploymentTargetDetailsResp == nil || deploymentTargetDetailsResp.Msg == nil {
  103. err := telemetry.Error(ctx, span, err, "deployment target details resp is nil")
  104. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  105. return
  106. }
  107. if deploymentTargetDetailsResp.Msg.ClusterId != int64(cluster.ID) {
  108. err := telemetry.Error(ctx, span, err, "deployment target details resp cluster id does not match cluster id")
  109. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  110. return
  111. }
  112. namespace := deploymentTargetDetailsResp.Msg.Namespace
  113. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "namespace", Value: namespace})
  114. if request.StartRange.IsZero() || request.EndRange.IsZero() {
  115. err := telemetry.Error(ctx, span, nil, "must provide start and end range")
  116. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  117. return
  118. }
  119. telemetry.WithAttributes(span,
  120. telemetry.AttributeKV{Key: "start-range", Value: request.StartRange.String()},
  121. telemetry.AttributeKV{Key: "end-range", Value: request.EndRange.String()},
  122. )
  123. k8sAgent, err := c.GetAgent(r, cluster, "")
  124. if err != nil {
  125. _ = telemetry.Error(ctx, span, err, "unable to get agent")
  126. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("unable to get agent"), http.StatusInternalServerError))
  127. return
  128. }
  129. agentSvc, err := porter_agent.GetAgentService(k8sAgent.Clientset)
  130. if err != nil {
  131. _ = telemetry.Error(ctx, span, err, "unable to get agent service")
  132. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("unable to get agent service"), http.StatusInternalServerError))
  133. return
  134. }
  135. matchLabels := map[string]string{
  136. lokiLabel_Namespace: namespace,
  137. lokiLabel_PorterAppName: appName,
  138. lokiLabel_PorterAppID: fmt.Sprintf("%d", request.AppID),
  139. }
  140. if request.ServiceName != "all" {
  141. matchLabels[lokiLabel_PorterServiceName] = request.ServiceName
  142. }
  143. if request.AppRevisionID != "" {
  144. matchLabels[lokiLabel_PorterAppRevisionID] = request.AppRevisionID
  145. }
  146. matchLabels[lokiLabel_DeploymentTargetId] = request.DeploymentTargetID
  147. logRequest := &types.LogRequest{
  148. Limit: request.Limit,
  149. StartRange: &request.StartRange,
  150. EndRange: &request.EndRange,
  151. MatchLabels: matchLabels,
  152. Direction: request.Direction,
  153. SearchParam: request.SearchParam,
  154. }
  155. logs, err := porter_agent.Logs(k8sAgent.Clientset, agentSvc, logRequest)
  156. if err != nil {
  157. _ = telemetry.Error(ctx, span, err, "unable to get logs")
  158. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("unable to get logs"), http.StatusInternalServerError))
  159. return
  160. }
  161. c.WriteResult(w, r, logs)
  162. }