Search in sources :

Example 1 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class CamelTypeProcessor method callCamel.

public NotificationHistory callCamel(Notification item, UUID historyId, JsonObject payload, String originalEventId) {
    final long startTime = System.currentTimeMillis();
    Endpoint endpoint = item.getEndpoint();
    String accountId = endpoint.getAccountId();
    // the next could give a CCE, but we only come here when it is a camel endpoint anyway
    String subType = endpoint.getSubType();
    CamelProperties camelProperties = endpoint.getProperties(CamelProperties.class);
    String integrationName = endpoint.getName();
    if (subType.equals("slack")) {
        // OpenBridge
        long endTime;
        NotificationHistory history = getHistoryStub(endpoint, item.getEvent(), 0L, historyId);
        try {
            callOpenBridge(payload, historyId, accountId, camelProperties, integrationName, originalEventId);
            history.setInvocationResult(true);
        } catch (Exception e) {
            history.setInvocationResult(false);
            Map<String, Object> details = new HashMap<>();
            details.put("failure", e.getMessage());
            history.setDetails(details);
            LOGGER.infof("SE: Sending event with historyId=%s and originalId=%s failed: %s ", historyId, originalEventId, e.getMessage());
        } finally {
            endTime = System.currentTimeMillis();
        }
        history.setInvocationTime(endTime - startTime);
        return history;
    } else {
        reallyCallCamel(payload, historyId, accountId, subType, integrationName, originalEventId);
        final long endTime = System.currentTimeMillis();
        // We only create a basic stub. The FromCamel filler will update it later
        NotificationHistory history = getHistoryStub(endpoint, item.getEvent(), endTime - startTime, historyId);
        return history;
    }
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory 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 3 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EndpointProcessor method process.

public void process(Event event) {
    processedItems.increment();
    List<Endpoint> endpoints = endpointRepository.getTargetEndpoints(event.getAccountId(), event.getEventType());
    // Target endpoints are grouped by endpoint type.
    endpointTargeted.increment(endpoints.size());
    Map<EndpointType, List<Endpoint>> endpointsByType = endpoints.stream().collect(Collectors.groupingBy(Endpoint::getType));
    for (Map.Entry<EndpointType, List<Endpoint>> entry : endpointsByType.entrySet()) {
        /*
             * For each endpoint type, the list of target endpoints is sent alongside with the action to the relevant processor.
             * Each processor returns a list of history entries. All of the returned lists are flattened into a single list.
             */
        EndpointTypeProcessor processor = endpointTypeToProcessor(entry.getKey());
        List<NotificationHistory> historyEntries = processor.process(event, entry.getValue());
        // Now each history entry is persisted.
        for (NotificationHistory history : historyEntries) {
            try {
                notificationHistoryRepository.createNotificationHistory(history);
            } catch (Exception e) {
                LOGGER.errorf("Notification history creation failed for %s", history.getEndpoint());
            }
        }
    }
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) EndpointTypeProcessor(com.redhat.cloud.notifications.processors.EndpointTypeProcessor) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) EndpointType(com.redhat.cloud.notifications.models.EndpointType) List(java.util.List) Map(java.util.Map)

Example 4 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class CamelTypeProcessorTest method testOBEndpointProcessing.

@Test
void testOBEndpointProcessing() {
    // We need input data for the test.
    Event event = buildEvent();
    event.setAccountId("rhid123");
    Endpoint endpoint = buildCamelEndpoint(event.getAction().getAccountId());
    endpoint.setSubType("slack");
    processor.obEnabled = true;
    bridgeHelper.setObEnabled(true);
    // Let's trigger the processing.
    // First with 'random OB endpoints', so we expect this to fail
    List<NotificationHistory> result = processor.process(event, List.of(endpoint));
    // One endpoint should have been processed.
    assertEquals(1, result.size());
    // Metrics should report the same thing.
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, SUB_TYPE);
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 1, SUB_TYPE_KEY, "slack");
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, "other-type");
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0);
    // Let's have a look at the first result entry fields.
    NotificationHistory historyItem = result.get(0);
    assertEquals(event, historyItem.getEvent());
    assertEquals(endpoint, historyItem.getEndpoint());
    assertEquals(CAMEL, historyItem.getEndpointType());
    assertEquals("slack", historyItem.getEndpointSubType());
    assertEquals(1, historyItem.getDetails().size());
    Map<String, Object> details = historyItem.getDetails();
    assertTrue(details.containsKey("failure"));
    // Now set up some mock OB endpoints (simulate valid bridge)
    String eventsEndpoint = getMockServerUrl() + "/events";
    System.out.println("==> Setting events endpoint to " + eventsEndpoint);
    Bridge bridge = new Bridge("321", eventsEndpoint, "my bridge");
    Map<String, String> auth = new HashMap<>();
    auth.put("access_token", "li-la-lu-token");
    Map<String, String> obProcessor = new HashMap<>();
    obProcessor.put("id", "p-my-id");
    MockServerConfig.addOpenBridgeEndpoints(auth, bridge);
    bridgeHelper.setOurBridge("321");
    System.out.println("==> Auth token " + bridgeHelper.getAuthToken());
    System.out.println("==> The bridge " + bridgeHelper.getBridgeIfNeeded());
    // Process again
    result = processor.process(event, List.of(endpoint));
    // One endpoint should have been processed.
    assertEquals(1, result.size());
    // Metrics should report the same thing.
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 2, SUB_TYPE_KEY, "slack");
    // Let's have a look at the first result entry fields.
    historyItem = result.get(0);
    assertEquals(event, historyItem.getEvent());
    assertEquals(endpoint, historyItem.getEndpoint());
    assertEquals(CAMEL, historyItem.getEndpointType());
    assertEquals("slack", historyItem.getEndpointSubType());
    assertNull(historyItem.getDetails());
    // Now try again, but the remote throws an error
    event.getAction().setAccountId("something-random");
    result = processor.process(event, List.of(endpoint));
    assertEquals(1, result.size());
    // Metrics should report the same thing.
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 3, SUB_TYPE_KEY, "slack");
    // Let's have a look at the first result entry fields.
    historyItem = result.get(0);
    assertEquals(event, historyItem.getEvent());
    assertEquals(1, historyItem.getDetails().size());
    details = historyItem.getDetails();
    assertTrue(details.containsKey("failure"));
    assertNotNull(historyItem.getInvocationTime());
    // The invocation will be complete when the response from Camel has been received.
    assertFalse(historyItem.isInvocationResult());
    MockServerConfig.clearOpenBridgeEndpoints(bridge);
    processor.obEnabled = false;
    bridgeHelper.setObEnabled(false);
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) HashMap(java.util.HashMap) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) Bridge(com.redhat.cloud.notifications.openbridge.Bridge) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest)

Example 5 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EmailTest method testEmailSubscriptionInstantWrongPayload.

@Test
@Disabled
void testEmailSubscriptionInstantWrongPayload() {
    mockGetUsers(8);
    final String tenant = "instant-email-tenant-wrong-payload";
    final String[] usernames = { "username-1", "username-2", "username-4" };
    String bundle = "rhel";
    String application = "policies";
    for (String username : usernames) {
        subscribe(tenant, username, bundle, application);
    }
    final List<String> bodyRequests = new ArrayList<>();
    ExpectationResponseCallback verifyEmptyRequest = req -> {
        assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
        assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
        assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
        bodyRequests.add(req.getBodyAsString());
        return response().withStatusCode(200);
    };
    HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
    Action emailActionMessage = new Action();
    emailActionMessage.setBundle(bundle);
    emailActionMessage.setApplication(application);
    emailActionMessage.setTimestamp(LocalDateTime.of(2020, 10, 3, 15, 22, 13, 25));
    emailActionMessage.setEventType(TestHelpers.eventType);
    emailActionMessage.setRecipients(List.of());
    emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id-wrong", "host-01").withAdditionalProperty("system_check_in-wrong", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name-wrong", "My test machine").withAdditionalProperty("tags-what?", List.of()).build());
    emailActionMessage.setEvents(List.of(new com.redhat.cloud.notifications.ingress.Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("foo", "bar").build()).build()));
    emailActionMessage.setAccountId(tenant);
    Event event = new Event();
    event.setAction(emailActionMessage);
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    Endpoint ep = new Endpoint();
    ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
    ep.setName("positive feeling");
    ep.setDescription("needle in the haystack");
    ep.setEnabled(true);
    ep.setProperties(properties);
    try {
        List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
            return emailProcessor.process(event, List.of(ep));
        });
        // The processor returns a null history value but Multi does not support null values so the resulting Multi is empty.
        assertTrue(historyEntries.isEmpty());
        // No email, invalid payload
        assertEquals(0, bodyRequests.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e);
    } finally {
        // Remove expectations
        MockServerLifecycleManager.getClient().clear(postReq);
    }
    clearSubscriptions();
}
Also used : INSTANT(com.redhat.cloud.notifications.models.EmailSubscriptionType.INSTANT) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) HttpRequest(org.mockserver.model.HttpRequest) Endpoint(com.redhat.cloud.notifications.models.Endpoint) ITUserResponse(com.redhat.cloud.notifications.recipients.itservice.pojo.response.ITUserResponse) LocalDateTime(java.time.LocalDateTime) Disabled(org.junit.jupiter.api.Disabled) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MockServerLifecycleManager(com.redhat.cloud.notifications.MockServerLifecycleManager) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) InjectSpy(io.quarkus.test.junit.mockito.InjectSpy) ITUserRequest(com.redhat.cloud.notifications.recipients.itservice.pojo.request.ITUserRequest) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Payload(com.redhat.cloud.notifications.ingress.Payload) Context(com.redhat.cloud.notifications.ingress.Context) InjectMock(io.quarkus.test.junit.mockito.InjectMock) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) Transactional(javax.transaction.Transactional) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) ITUserService(com.redhat.cloud.notifications.recipients.itservice.ITUserService) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) Mockito(org.mockito.Mockito) List(java.util.List) Authentication(com.redhat.cloud.notifications.recipients.itservice.pojo.response.Authentication) EndpointType(com.redhat.cloud.notifications.models.EndpointType) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AccountRelationship(com.redhat.cloud.notifications.recipients.itservice.pojo.response.AccountRelationship) TestHelpers(com.redhat.cloud.notifications.TestHelpers) Metadata(com.redhat.cloud.notifications.ingress.Metadata) Action(com.redhat.cloud.notifications.ingress.Action) Comparator(java.util.Comparator) HttpResponse.response(org.mockserver.model.HttpResponse.response) PersonalInformation(com.redhat.cloud.notifications.recipients.itservice.pojo.response.PersonalInformation) HttpRequest(org.mockserver.model.HttpRequest) Action(com.redhat.cloud.notifications.ingress.Action) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) ArrayList(java.util.ArrayList) Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Aggregations

NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)16 Endpoint (com.redhat.cloud.notifications.models.Endpoint)14 Event (com.redhat.cloud.notifications.models.Event)10 JsonObject (io.vertx.core.json.JsonObject)9 LocalDateTime (java.time.LocalDateTime)8 Test (org.junit.jupiter.api.Test)8 Action (com.redhat.cloud.notifications.ingress.Action)7 List (java.util.List)7 Inject (javax.inject.Inject)7 Context (com.redhat.cloud.notifications.ingress.Context)6 QuarkusTest (io.quarkus.test.junit.QuarkusTest)6 EndpointType (com.redhat.cloud.notifications.models.EndpointType)5 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)4 Metadata (com.redhat.cloud.notifications.ingress.Metadata)4 Payload (com.redhat.cloud.notifications.ingress.Payload)4 Arrays (java.util.Arrays)4 Map (java.util.Map)4 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)4 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)4