app_notifications.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package porter_app
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/authz"
  6. "github.com/porter-dev/porter/api/server/shared/requestutils"
  7. "connectrpc.com/connect"
  8. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  9. "github.com/google/uuid"
  10. "github.com/porter-dev/porter/internal/porter_app"
  11. "github.com/porter-dev/porter/internal/porter_app/notifications"
  12. "github.com/porter-dev/porter/internal/repository"
  13. "github.com/porter-dev/porter/internal/telemetry"
  14. "github.com/porter-dev/porter/api/server/handlers"
  15. "github.com/porter-dev/porter/api/server/shared"
  16. "github.com/porter-dev/porter/api/server/shared/apierrors"
  17. "github.com/porter-dev/porter/api/server/shared/config"
  18. "github.com/porter-dev/porter/api/types"
  19. "github.com/porter-dev/porter/internal/models"
  20. )
  21. // AppNotificationsHandler handles requests to the /apps/{porter_app_name}/notifications endpoint
  22. type AppNotificationsHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. authz.KubernetesAgentGetter
  25. }
  26. // NewAppNotificationsHandler returns a new AppNotificationsHandler
  27. func NewAppNotificationsHandler(
  28. config *config.Config,
  29. decoderValidator shared.RequestDecoderValidator,
  30. writer shared.ResultWriter,
  31. ) *AppNotificationsHandler {
  32. return &AppNotificationsHandler{
  33. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  34. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  35. }
  36. }
  37. // AppNotificationsRequest is the request object for the /apps/{porter_app_name}/notifications endpoint
  38. type AppNotificationsRequest struct {
  39. DeploymentTargetID string `schema:"deployment_target_id"`
  40. }
  41. // AppNotificationsResponse is the response object for the /apps/{porter_app_name}/notifications endpoint
  42. type AppNotificationsResponse struct {
  43. // Notifications are the notifications associated with the app revision
  44. Notifications []notifications.Notification `json:"notifications"`
  45. }
  46. func (c *AppNotificationsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  47. ctx, span := telemetry.NewSpan(r.Context(), "serve-app-notifications")
  48. defer span.End()
  49. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  50. appName, reqErr := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
  51. if reqErr != nil {
  52. e := telemetry.Error(ctx, span, reqErr, "error parsing stack name from url")
  53. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusBadRequest))
  54. return
  55. }
  56. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-name", Value: appName})
  57. request := &AppNotificationsRequest{}
  58. if ok := c.DecodeAndValidate(w, r, request); !ok {
  59. err := telemetry.Error(ctx, span, nil, "error decoding request")
  60. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  61. return
  62. }
  63. _, err := uuid.Parse(request.DeploymentTargetID)
  64. if err != nil {
  65. err := telemetry.Error(ctx, span, err, "error parsing deployment target id")
  66. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  67. return
  68. }
  69. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "deployment-target-id", Value: request.DeploymentTargetID})
  70. porterApps, err := c.Repo().PorterApp().ReadPorterAppsByProjectIDAndName(project.ID, appName)
  71. if err != nil {
  72. err := telemetry.Error(ctx, span, err, "error getting porter apps")
  73. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  74. return
  75. }
  76. if len(porterApps) == 0 {
  77. err := telemetry.Error(ctx, span, err, "no porter apps returned")
  78. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  79. return
  80. }
  81. if len(porterApps) > 1 {
  82. err := telemetry.Error(ctx, span, err, "multiple porter apps returned; unable to determine which one to use")
  83. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  84. return
  85. }
  86. appId := porterApps[0].ID
  87. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-id", Value: appId})
  88. if appId == 0 {
  89. err := telemetry.Error(ctx, span, err, "porter app id is missing")
  90. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  91. return
  92. }
  93. listAppRevisionsReq := connect.NewRequest(&porterv1.ListAppRevisionsRequest{
  94. ProjectId: int64(project.ID),
  95. AppId: int64(appId),
  96. DeploymentTargetIdentifier: &porterv1.DeploymentTargetIdentifier{Id: request.DeploymentTargetID},
  97. })
  98. listAppRevisionsResp, err := c.Config().ClusterControlPlaneClient.ListAppRevisions(ctx, listAppRevisionsReq)
  99. if err != nil {
  100. err = telemetry.Error(ctx, span, err, "error listing app revisions")
  101. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  102. return
  103. }
  104. if listAppRevisionsResp == nil || listAppRevisionsResp.Msg == nil {
  105. err = telemetry.Error(ctx, span, nil, "list app revisions response is nil")
  106. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  107. return
  108. }
  109. appRevisionsList := listAppRevisionsResp.Msg.AppRevisions
  110. latestNotifications := make([]notifications.Notification, 0)
  111. encodedRevisions := make([]porter_app.Revision, 0)
  112. if len(appRevisionsList) > 0 {
  113. encodedRevision, err := porter_app.EncodedRevisionFromProto(ctx, appRevisionsList[0])
  114. if err != nil {
  115. err := telemetry.Error(ctx, span, err, "error getting encoded revision from proto")
  116. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  117. return
  118. }
  119. encodedRevisions = append(encodedRevisions, encodedRevision)
  120. // encode the penultimate revision as well in case it is a rollback
  121. if len(appRevisionsList) > 1 {
  122. penultimateRevision, err := porter_app.EncodedRevisionFromProto(ctx, appRevisionsList[1])
  123. if err != nil {
  124. err := telemetry.Error(ctx, span, err, "error getting encoded revision from proto")
  125. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  126. return
  127. }
  128. encodedRevisions = append(encodedRevisions, penultimateRevision)
  129. }
  130. }
  131. if len(encodedRevisions) > 0 {
  132. latestNotifications, err = notificationsForRevision(ctx, notificationsForRevisionInput{
  133. Revision: encodedRevisions[0],
  134. PorterAppEventRepository: c.Repo().PorterAppEvent(),
  135. })
  136. if err != nil {
  137. err := telemetry.Error(ctx, span, err, "error getting notifications for revision")
  138. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  139. return
  140. }
  141. // if the penultimate revision is a rollback, get the notifications for that revision as well so we can show the user why the rollback happened
  142. if len(encodedRevisions) > 1 && encodedRevisions[1].Status == models.AppRevisionStatus_RollbackSuccessful {
  143. rollbackNotifications, err := notificationsForRevision(ctx, notificationsForRevisionInput{
  144. Revision: encodedRevisions[1],
  145. PorterAppEventRepository: c.Repo().PorterAppEvent(),
  146. })
  147. if err != nil {
  148. err := telemetry.Error(ctx, span, err, "error getting notifications for rollback revision")
  149. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  150. return
  151. }
  152. latestNotifications = append(latestNotifications, rollbackNotifications...)
  153. }
  154. }
  155. response := AppNotificationsResponse{
  156. Notifications: latestNotifications,
  157. }
  158. c.WriteResult(w, r, response)
  159. }
  160. type notificationsForRevisionInput struct {
  161. Revision porter_app.Revision
  162. PorterAppEventRepository repository.PorterAppEventRepository
  163. }
  164. func notificationsForRevision(ctx context.Context, inp notificationsForRevisionInput) ([]notifications.Notification, error) {
  165. ctx, span := telemetry.NewSpan(ctx, "notifications-for-revision")
  166. defer span.End()
  167. telemetry.WithAttributes(span,
  168. telemetry.AttributeKV{Key: "app-revision-id", Value: inp.Revision.ID},
  169. telemetry.AttributeKV{Key: "app-instance-id", Value: inp.Revision.AppInstanceID},
  170. )
  171. notificationList := make([]notifications.Notification, 0)
  172. if inp.Revision.ID == "" {
  173. return notificationList, telemetry.Error(ctx, span, nil, "app revision id is missing")
  174. }
  175. if inp.Revision.AppInstanceID == uuid.Nil {
  176. return notificationList, telemetry.Error(ctx, span, nil, "app instance id is missing")
  177. }
  178. appRevisionId := inp.Revision.ID
  179. appInstanceId := inp.Revision.AppInstanceID
  180. notificationEvents, err := inp.PorterAppEventRepository.ReadNotificationsByAppRevisionID(ctx, appInstanceId, appRevisionId)
  181. if err != nil {
  182. return notificationList, telemetry.Error(ctx, span, err, "error getting notifications from repo")
  183. }
  184. for _, event := range notificationEvents {
  185. notification, err := notifications.NotificationFromPorterAppEvent(event)
  186. if err != nil {
  187. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: err.Error()})
  188. continue
  189. }
  190. if notification == nil {
  191. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: "notification is nil"})
  192. continue
  193. }
  194. // TODO: remove this check once this attribute is not found in the span for >30 days
  195. if notification.Scope == "" {
  196. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: "old-notification-format"})
  197. continue
  198. }
  199. notificationList = append(notificationList, *notification)
  200. }
  201. return notificationList, nil
  202. }