Search in sources :

Example 1 with Action

use of com.redhat.cloud.notifications.ingress.Action in project notifications-backend by RedHatInsights.

the class EmailSubscriptionTypeProcessor method sendEmail.

private List<NotificationHistory> sendEmail(Event event, Set<Endpoint> endpoints, EmailTemplate emailTemplate) {
    EmailSubscriptionType emailSubscriptionType = EmailSubscriptionType.INSTANT;
    processedEmailCount.increment();
    Action action = event.getAction();
    TemplateInstance subject;
    TemplateInstance body;
    if (useTemplatesFromDb) {
        Optional<InstantEmailTemplate> instantEmailTemplate = templateRepository.findInstantEmailTemplate(event.getEventType().getId());
        if (instantEmailTemplate.isEmpty()) {
            return Collections.emptyList();
        } else {
            String subjectData = instantEmailTemplate.get().getSubjectTemplate().getData();
            subject = templateService.compileTemplate(subjectData, "subject");
            String bodyData = instantEmailTemplate.get().getBodyTemplate().getData();
            body = templateService.compileTemplate(bodyData, "body");
        }
    } else {
        if (!emailTemplate.isSupported(action.getEventType(), emailSubscriptionType)) {
            return Collections.emptyList();
        }
        subject = emailTemplate.getTitle(action.getEventType(), emailSubscriptionType);
        body = emailTemplate.getBody(action.getEventType(), emailSubscriptionType);
    }
    if (subject == null || body == null) {
        return Collections.emptyList();
    }
    Set<RecipientSettings> requests = Stream.concat(endpoints.stream().map(EndpointRecipientSettings::new), ActionRecipientSettings.fromAction(action).stream()).collect(Collectors.toSet());
    Set<String> subscribers = Set.copyOf(emailSubscriptionRepository.getEmailSubscribersUserId(action.getAccountId(), action.getBundle(), action.getApplication(), emailSubscriptionType));
    LOG.info("sending email for event: " + event);
    return recipientResolver.recipientUsers(action.getAccountId(), action.getOrgId(), requests, subscribers).stream().map(user -> emailSender.sendEmail(user, event, subject, body)).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
Also used : Arrays(java.util.Arrays) Endpoint(com.redhat.cloud.notifications.models.Endpoint) BaseTransformer(com.redhat.cloud.notifications.transformers.BaseTransformer) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) EmailTemplateFactory(com.redhat.cloud.notifications.templates.EmailTemplateFactory) EmailTemplate(com.redhat.cloud.notifications.templates.EmailTemplate) Map(java.util.Map) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) User(com.redhat.cloud.notifications.recipients.User) ZoneOffset(java.time.ZoneOffset) Context(com.redhat.cloud.notifications.ingress.Context) Counter(io.micrometer.core.instrument.Counter) TemplateInstance(io.quarkus.qute.TemplateInstance) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) Set(java.util.Set) UUID(java.util.UUID) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) AggregationCommand(com.redhat.cloud.notifications.models.AggregationCommand) Incoming(org.eclipse.microprofile.reactive.messaging.Incoming) AggregationEmailTemplate(com.redhat.cloud.notifications.models.AggregationEmailTemplate) Logger(org.jboss.logging.Logger) LocalDateTime(java.time.LocalDateTime) USE_TEMPLATES_FROM_DB_KEY(com.redhat.cloud.notifications.templates.TemplateService.USE_TEMPLATES_FROM_DB_KEY) TemplateService(com.redhat.cloud.notifications.templates.TemplateService) Inject(javax.inject.Inject) EmailAggregationRepository(com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Blocking(io.smallrye.reactive.messaging.annotations.Blocking) Acknowledgment(org.eclipse.microprofile.reactive.messaging.Acknowledgment) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EmailAggregationKey(com.redhat.cloud.notifications.models.EmailAggregationKey) EndpointTypeProcessor(com.redhat.cloud.notifications.processors.EndpointTypeProcessor) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) TemplateRepository(com.redhat.cloud.notifications.db.repositories.TemplateRepository) RecipientResolver(com.redhat.cloud.notifications.recipients.RecipientResolver) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Action(com.redhat.cloud.notifications.ingress.Action) Collections(java.util.Collections) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) Action(com.redhat.cloud.notifications.ingress.Action) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Optional(java.util.Optional) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) TemplateInstance(io.quarkus.qute.TemplateInstance)

Example 2 with Action

use of com.redhat.cloud.notifications.ingress.Action in project notifications-backend by RedHatInsights.

the class FromCamelHistoryFiller method reinjectIfNeeded.

private void reinjectIfNeeded(Map<String, Object> payloadMap) {
    if (!enableReInject || (payloadMap.containsKey("successful") && ((Boolean) payloadMap.get("successful")))) {
        return;
    }
    String historyId = (String) payloadMap.get("historyId");
    log.infof("Notification with id %s was not successful, resubmitting for further processing", historyId);
    Endpoint ep = notificationHistoryRepository.getEndpointForHistoryId(historyId);
    Event event = new Event();
    Payload.PayloadBuilder payloadBuilder = new Payload.PayloadBuilder();
    payloadMap.forEach(payloadBuilder::withAdditionalProperty);
    // TODO augment with details from Endpoint and original event
    event.setPayload(payloadBuilder.build());
    // Save the original id, as we may need it in the future.
    Context.ContextBuilder contextBuilder = new Context.ContextBuilder();
    contextBuilder.withAdditionalProperty("original-id", historyId);
    if (ep != null) {
        // TODO For the current tests. EP should not be null in real life
        contextBuilder.withAdditionalProperty("failed-integration", ep.getName());
    }
    Action action = new Action.ActionBuilder().withId(UUID.randomUUID()).withBundle("console").withApplication("notifications").withEventType("integration-failed").withAccountId(ep != null ? ep.getAccountId() : "").withContext(contextBuilder.build()).withTimestamp(LocalDateTime.now(ZoneOffset.UTC)).withEvents(Collections.singletonList(event)).withRecipients(Collections.singletonList(new Recipient.RecipientBuilder().withOnlyAdmins(true).withIgnoreUserPreferences(true).build())).build();
    String ser = Parser.encode(action);
    // Add the message id in Kafka header for the de-duplicator
    Message<String> message = buildMessageWithId(ser);
    emitter.send(message);
}
Also used : Context(com.redhat.cloud.notifications.ingress.Context) Action(com.redhat.cloud.notifications.ingress.Action) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Event(com.redhat.cloud.notifications.ingress.Event) Payload(com.redhat.cloud.notifications.ingress.Payload)

Example 3 with Action

use of com.redhat.cloud.notifications.ingress.Action in project notifications-backend by RedHatInsights.

the class TestHelpers method createEmailAggregation.

static EmailAggregation createEmailAggregation(String tenant, String orgId, String bundle, String application, String policyId, String inventoryId) {
    EmailAggregation aggregation = new EmailAggregation();
    aggregation.setBundleName(bundle);
    aggregation.setApplicationName(application);
    aggregation.setAccountId(tenant);
    aggregation.setOrgId(orgId);
    aggregation.setCreated(LocalDateTime.now(UTC).minusHours(5L));
    Action emailActionMessage = new Action();
    emailActionMessage.setBundle(bundle);
    emailActionMessage.setApplication(application);
    emailActionMessage.setTimestamp(LocalDateTime.now());
    emailActionMessage.setEventType("testEmailSubscriptionInstant");
    emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id", inventoryId).withAdditionalProperty("system_check_in", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name", "My test machine").withAdditionalProperty("tags", List.of()).build());
    emailActionMessage.setEvents(List.of(new Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("policy_id", policyId).withAdditionalProperty("policy_name", "not-tested-name").withAdditionalProperty("policy_description", "not-used-desc").withAdditionalProperty("policy_condition", "not-used-condition").build()).build()));
    emailActionMessage.setAccountId(tenant);
    JsonObject payload = baseTransformer.transform(emailActionMessage);
    aggregation.setPayload(payload);
    return aggregation;
}
Also used : Action(com.redhat.cloud.notifications.ingress.Action) Event(com.redhat.cloud.notifications.ingress.Event) JsonObject(io.vertx.core.json.JsonObject) Payload(com.redhat.cloud.notifications.ingress.Payload) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation)

Example 4 with Action

use of com.redhat.cloud.notifications.ingress.Action in project notifications-backend by RedHatInsights.

the class EventConsumerTest method testInvalidMessageId.

@Test
void testInvalidMessageId() {
    EventType eventType = mockGetEventTypeAndCreateEvent();
    Action action = buildValidAction();
    String payload = serializeAction(action);
    Message<String> message = buildMessageWithId("I am not a valid UUID!".getBytes(UTF_8), payload);
    inMemoryConnector.source(INGRESS_CHANNEL).send(message);
    micrometerAssertionHelper.awaitAndAssertTimerIncrement(CONSUMED_TIMER_NAME, 1);
    assertEquals(1L, registry.timer(CONSUMED_TIMER_NAME, "bundle", action.getBundle(), "application", action.getApplication()).count());
    micrometerAssertionHelper.assertCounterIncrement(MESSAGE_ID_INVALID_COUNTER_NAME, 1);
    assertNoCounterIncrement(REJECTED_COUNTER_NAME, PROCESSING_ERROR_COUNTER_NAME, PROCESSING_EXCEPTION_COUNTER_NAME, DUPLICATE_COUNTER_NAME, MESSAGE_ID_VALID_COUNTER_NAME, MESSAGE_ID_MISSING_COUNTER_NAME);
    verifyExactlyOneProcessing(eventType, payload, action);
    verify(kafkaMessageDeduplicator, times(1)).registerMessageId(null);
}
Also used : TestHelpers.serializeAction(com.redhat.cloud.notifications.TestHelpers.serializeAction) Action(com.redhat.cloud.notifications.ingress.Action) EventType(com.redhat.cloud.notifications.models.EventType) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest)

Example 5 with Action

use of com.redhat.cloud.notifications.ingress.Action in project notifications-backend by RedHatInsights.

the class EventConsumerTest method testProcessingErrorWithoutMessageId.

@Test
void testProcessingErrorWithoutMessageId() {
    EventType eventType = mockGetEventTypeAndCreateEvent();
    mockProcessingFailure();
    Action action = buildValidAction();
    String payload = serializeAction(action);
    inMemoryConnector.source(INGRESS_CHANNEL).send(payload);
    micrometerAssertionHelper.awaitAndAssertTimerIncrement(CONSUMED_TIMER_NAME, 1);
    assertEquals(1L, registry.timer(CONSUMED_TIMER_NAME, "bundle", action.getBundle(), "application", action.getApplication()).count());
    micrometerAssertionHelper.assertCounterIncrement(MESSAGE_ID_MISSING_COUNTER_NAME, 1);
    micrometerAssertionHelper.assertCounterIncrement(PROCESSING_ERROR_COUNTER_NAME, 1);
    assertNoCounterIncrement(REJECTED_COUNTER_NAME, DUPLICATE_COUNTER_NAME, MESSAGE_ID_VALID_COUNTER_NAME, MESSAGE_ID_INVALID_COUNTER_NAME);
    verifyExactlyOneProcessing(eventType, payload, action);
    verify(kafkaMessageDeduplicator, times(1)).registerMessageId(null);
}
Also used : TestHelpers.serializeAction(com.redhat.cloud.notifications.TestHelpers.serializeAction) Action(com.redhat.cloud.notifications.ingress.Action) EventType(com.redhat.cloud.notifications.models.EventType) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest)

Aggregations

Action (com.redhat.cloud.notifications.ingress.Action)49 Test (org.junit.jupiter.api.Test)22 QuarkusTest (io.quarkus.test.junit.QuarkusTest)20 Payload (com.redhat.cloud.notifications.ingress.Payload)19 JsonObject (io.vertx.core.json.JsonObject)17 Event (com.redhat.cloud.notifications.ingress.Event)15 Context (com.redhat.cloud.notifications.ingress.Context)14 EmailAggregation (com.redhat.cloud.notifications.models.EmailAggregation)12 Event (com.redhat.cloud.notifications.models.Event)12 TestHelpers.serializeAction (com.redhat.cloud.notifications.TestHelpers.serializeAction)9 Endpoint (com.redhat.cloud.notifications.models.Endpoint)8 EventType (com.redhat.cloud.notifications.models.EventType)7 NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)7 LocalDateTime (java.time.LocalDateTime)7 JsonArray (io.vertx.core.json.JsonArray)6 List (java.util.List)6 Collectors (java.util.stream.Collectors)6 Inject (javax.inject.Inject)6 TemplateInstance (io.quarkus.qute.TemplateInstance)5 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)4