Search in sources :

Example 6 with EventDefinitionDto

use of org.graylog.events.processor.EventDefinitionDto in project graylog2-server by Graylog2.

the class LegacyAlarmCallbackEventNotification method execute.

@Override
public void execute(EventNotificationContext ctx) throws PermanentEventNotificationException {
    final LegacyAlarmCallbackEventNotificationConfig config = (LegacyAlarmCallbackEventNotificationConfig) ctx.notificationConfig();
    final ImmutableList<MessageSummary> messagesForEvent = notificationCallbackService.getBacklogForEvent(ctx);
    final Optional<EventDefinitionDto> optionalEventDefinition = ctx.eventDefinition();
    if (!optionalEventDefinition.isPresent()) {
        final String msg = String.format(Locale.ROOT, "Unable to find definition for event <%s>", ctx.event().id());
        LOG.error(msg);
        throw new PermanentEventNotificationException(msg);
    }
    try {
        alarmCallbackSender.send(config, optionalEventDefinition.get(), ctx.event(), messagesForEvent);
    } catch (Exception e) {
        // TODO: Is there a case where we want to retry? (and are able to detect when to do it)
        throw new PermanentEventNotificationException("Couldn't send legacy notification - legacy notifications cannot be retried!", e);
    }
}
Also used : EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto) PermanentEventNotificationException(org.graylog.events.notifications.PermanentEventNotificationException) MessageSummary(org.graylog2.plugin.MessageSummary) PermanentEventNotificationException(org.graylog.events.notifications.PermanentEventNotificationException)

Example 7 with EventDefinitionDto

use of org.graylog.events.processor.EventDefinitionDto in project graylog2-server by Graylog2.

the class EventNotificationExecutionJob method execute.

@Override
public JobTriggerUpdate execute(JobExecutionContext ctx) throws JobExecutionException {
    Optional<EventDefinitionDto> optionalEventDefinition;
    long gracePeriodInMS = 0;
    final JobTriggerDto trigger = ctx.trigger();
    final Optional<Data> optionalData = trigger.data().map(d -> (Data) d);
    if (!optionalData.isPresent()) {
        throw new JobExecutionException("Missing notification job data for notification <" + jobConfig.notificationId() + ">, unable to execute notification: " + ctx.definition().title(), trigger, JobTriggerUpdate.withoutNextTime());
    }
    final Data data = optionalData.get();
    final EventDto eventDto = data.eventDto();
    final NotificationDto notification = notificationService.get(jobConfig.notificationId()).orElseThrow(() -> new JobExecutionException("Couldn't find notification <" + jobConfig.notificationId() + ">", trigger, JobTriggerUpdate.withError(trigger)));
    final EventNotification.Factory eventNotificationFactory = eventNotificationFactories.get(notification.config().type());
    if (eventNotificationFactory == null) {
        throw new JobExecutionException("Couldn't find factory for notification type <" + notification.config().type() + ">", trigger, ctx.jobTriggerUpdates().scheduleNextExecution());
    }
    final EventNotification eventNotification = eventNotificationFactory.create();
    metrics.registerEventNotification(eventNotification, notification);
    try {
        optionalEventDefinition = Optional.ofNullable(getEventDefinition(eventDto));
        if (optionalEventDefinition.isPresent()) {
            gracePeriodInMS = optionalEventDefinition.get().notificationSettings().gracePeriodMs();
        }
    } catch (NotFoundException e) {
        LOG.error("Couldn't find event definition with ID <{}>.", eventDto.eventDefinitionId());
        optionalEventDefinition = Optional.empty();
    }
    EventNotificationContext notificationContext = EventNotificationContext.builder().notificationId(notification.id()).notificationConfig(notification.config()).event(eventDto).eventDefinition(optionalEventDefinition.get()).jobTrigger(trigger).build();
    updateTriggerStatus(eventDto, gracePeriodInMS);
    if (inGrace(eventDto, gracePeriodInMS)) {
        LOG.debug("Notification <{}> triggered but it's in grace period.", jobConfig.notificationId());
        metrics.markInGrace(eventNotification, notification);
        return ctx.jobTriggerUpdates().scheduleNextExecution();
    }
    try {
        metrics.markExecution(eventNotification, notification);
        eventNotification.execute(notificationContext);
        metrics.markSuccess(eventNotification, notification);
    } catch (TemporaryEventNotificationException e) {
        metrics.markFailedTemporarily(eventNotification, notification);
        final long retryPeriod = configurationProvider.get().eventNotificationsRetry();
        throw new JobExecutionException(String.format(Locale.ROOT, "Failed to execute notification, retrying in %d minutes - <%s/%s/%s>", TimeUnit.MILLISECONDS.toMinutes(retryPeriod), notification.id(), notification.title(), notification.config().type()), trigger, ctx.jobTriggerUpdates().retryIn(retryPeriod, TimeUnit.MILLISECONDS), e);
    } catch (PermanentEventNotificationException e) {
        metrics.markFailedPermanently(eventNotification, notification);
        throw new JobExecutionException(String.format(Locale.ROOT, "Failed permanently to execute notification, giving up - <%s/%s/%s>", notification.id(), notification.title(), notification.config().type()), trigger, ctx.jobTriggerUpdates().scheduleNextExecution(), e);
    } catch (EventNotificationException e) {
        metrics.markFailed(eventNotification, notification);
        throw new JobExecutionException(String.format(Locale.ROOT, "Notification failed to execute - <%s/%s/%s>", notification.id(), notification.title(), notification.config().type()), trigger, ctx.jobTriggerUpdates().scheduleNextExecution(), e);
    }
    updateNotifiedStatus(eventDto, gracePeriodInMS);
    return ctx.jobTriggerUpdates().scheduleNextExecution();
}
Also used : EventDto(org.graylog.events.event.EventDto) NotFoundException(org.graylog2.database.NotFoundException) JobTriggerData(org.graylog.scheduler.JobTriggerData) JobTriggerDto(org.graylog.scheduler.JobTriggerDto) JobExecutionException(org.graylog.scheduler.JobExecutionException) EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto)

Example 8 with EventDefinitionDto

use of org.graylog.events.processor.EventDefinitionDto in project graylog2-server by Graylog2.

the class NotificationResourceHandler method delete.

/**
 * Deletes an existing notification definition and its corresponding scheduler job definition and trigger.
 *
 * @param dtoId the notification definition to delete
 * @return true if the notification definition got deleted, false otherwise
 */
public boolean delete(String dtoId) {
    final Optional<NotificationDto> dto = notificationService.get(dtoId);
    if (!dto.isPresent()) {
        return false;
    }
    jobDefinitionService.getByConfigField(EventNotificationConfig.FIELD_NOTIFICATION_ID, dtoId).ifPresent(jobDefinition -> {
        LOG.debug("Deleting job definition <{}/{}> for notification <{}/{}>", jobDefinition.id(), jobDefinition.title(), dto.get().id(), dto.get().title());
        jobDefinitionService.delete(jobDefinition.id());
    });
    // Delete notification from existing events
    eventDefinitionService.getByNotificationId(dtoId).forEach(eventDefinition -> {
        LOG.debug("Removing notification <{}/{}> from event definition <{}/{}>", dto.get().id(), dto.get().title(), eventDefinition.id(), eventDefinition.title());
        final ImmutableList<EventNotificationHandler.Config> notifications = eventDefinition.notifications().stream().filter(entry -> !entry.notificationId().equals(dtoId)).collect(ImmutableList.toImmutableList());
        EventDefinitionDto updatedEventDto = eventDefinition.toBuilder().notifications(notifications).build();
        eventDefinitionService.save(updatedEventDto);
    });
    LOG.debug("Deleting notification definition <{}/{}>", dto.get().id(), dto.get().title());
    return notificationService.delete(dtoId) > 0;
}
Also used : Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NotFoundException(javax.ws.rs.NotFoundException) Inject(javax.inject.Inject) JobDefinitionDto(org.graylog.scheduler.JobDefinitionDto) ImmutableList(com.google.common.collect.ImmutableList) DBEventDefinitionService(org.graylog.events.processor.DBEventDefinitionService) Map(java.util.Map) DBJobDefinitionService(org.graylog.scheduler.DBJobDefinitionService) Optional(java.util.Optional) User(org.graylog2.plugin.database.users.User) EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto) EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto)

Example 9 with EventDefinitionDto

use of org.graylog.events.processor.EventDefinitionDto in project graylog2-server by Graylog2.

the class NotificationTestData method getDummyContext.

public static EventNotificationContext getDummyContext(NotificationDto notificationDto, String userName) {
    final EventDto eventDto = EventDto.builder().alert(true).eventDefinitionId("EventDefinitionTestId").eventDefinitionType("notification-test-v1").eventTimestamp(Tools.nowUTC()).processingTimestamp(Tools.nowUTC()).id("TEST_NOTIFICATION_ID").streams(ImmutableSet.of(Stream.DEFAULT_EVENTS_STREAM_ID)).message("Notification test message triggered from user <" + userName + ">").source(Stream.DEFAULT_STREAM_ID).keyTuple(ImmutableList.of("testkey")).key("testkey").originContext(EventOriginContext.elasticsearchMessage("testIndex_42", "b5e53442-12bb-4374-90ed-0deadbeefbaz")).priority(2).fields(ImmutableMap.of("field1", "value1", "field2", "value2")).build();
    final EventDefinitionDto eventDefinitionDto = EventDefinitionDto.builder().alert(true).id(TEST_NOTIFICATION_ID).title("Event Definition Test Title").description("Event Definition Test Description").config(new EventProcessorConfig() {

        @Override
        public String type() {
            return "test-dummy-v1";
        }

        @Override
        public ValidationResult validate() {
            return null;
        }

        @Override
        public EventProcessorConfigEntity toContentPackEntity(EntityDescriptorIds entityDescriptorIds) {
            return null;
        }
    }).fieldSpec(ImmutableMap.of()).priority(2).keySpec(ImmutableList.of()).notificationSettings(new EventNotificationSettings() {

        @Override
        public long gracePeriodMs() {
            return 0;
        }

        @Override
        public // disable to avoid errors in getBacklogForEvent()
        long backlogSize() {
            return 0;
        }

        @Override
        public Builder toBuilder() {
            return null;
        }
    }).build();
    return EventNotificationContext.builder().notificationId(TEST_NOTIFICATION_ID).notificationConfig(notificationDto.config()).event(eventDto).eventDefinition(eventDefinitionDto).build();
}
Also used : EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto) EntityDescriptorIds(org.graylog2.contentpacks.EntityDescriptorIds) EventDto(org.graylog.events.event.EventDto) EventProcessorConfig(org.graylog.events.processor.EventProcessorConfig)

Example 10 with EventDefinitionDto

use of org.graylog.events.processor.EventDefinitionDto in project graylog2-server by Graylog2.

the class AggregationEventProcessorTest method testEventsFromAggregationResultWithEmptyResultUsesEventDefinitionStreamAsSourceStreams.

@Test
public void testEventsFromAggregationResultWithEmptyResultUsesEventDefinitionStreamAsSourceStreams() {
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.plusHours(1));
    // We expect to get the end of the aggregation timerange as event time
    final TestEvent event1 = new TestEvent(timerange.to());
    final TestEvent event2 = new TestEvent(timerange.to());
    when(eventFactory.createEvent(any(EventDefinition.class), eq(now), anyString())).thenReturn(// first invocation return value
    event1).thenReturn(// second invocation return value
    event2);
    final EventDefinitionDto eventDefinitionDto = buildEventDefinitionDto(ImmutableSet.of("stream-2"), ImmutableList.of(), null);
    final AggregationEventProcessorParameters parameters = AggregationEventProcessorParameters.builder().timerange(timerange).build();
    final AggregationEventProcessor eventProcessor = new AggregationEventProcessor(eventDefinitionDto, searchFactory, eventProcessorDependencyCheck, stateService, moreSearch, streamService, messages);
    final AggregationResult result = buildAggregationResult(timerange, now, ImmutableList.of("one", "two"));
    final ImmutableList<EventWithContext> eventsWithContext = eventProcessor.eventsFromAggregationResult(eventFactory, parameters, result);
    assertThat(eventsWithContext).hasSize(1);
    assertThat(eventsWithContext.get(0)).satisfies(eventWithContext -> {
        final Event event = eventWithContext.event();
        assertThat(event.getId()).isEqualTo(event1.getId());
        assertThat(event.getMessage()).isEqualTo(event1.getMessage());
        assertThat(event.getEventTimestamp()).isEqualTo(timerange.to());
        assertThat(event.getTimerangeStart()).isEqualTo(timerange.from());
        assertThat(event.getTimerangeEnd()).isEqualTo(timerange.to());
        // Must contain the stream from the event definition because there is none in the result
        assertThat(event.getSourceStreams()).containsOnly("stream-2");
        final Message message = eventWithContext.messageContext().orElse(null);
        assertThat(message).isNotNull();
        assertThat(message.getField("group_field_one")).isEqualTo("one");
        assertThat(message.getField("group_field_two")).isEqualTo("two");
        assertThat(message.getField("aggregation_key")).isEqualTo("one|two");
        assertThat(message.getField("aggregation_value_count")).isEqualTo(0.0d);
    });
}
Also used : EventDefinitionDto(org.graylog.events.processor.EventDefinitionDto) Message(org.graylog2.plugin.Message) TestEvent(org.graylog.events.event.TestEvent) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) Event(org.graylog.events.event.Event) TestEvent(org.graylog.events.event.TestEvent) EventWithContext(org.graylog.events.event.EventWithContext) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Aggregations

EventDefinitionDto (org.graylog.events.processor.EventDefinitionDto)25 Test (org.junit.Test)10 AbsoluteRange (org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange)7 DateTime (org.joda.time.DateTime)7 TestEvent (org.graylog.events.event.TestEvent)5 Event (org.graylog.events.event.Event)4 EventWithContext (org.graylog.events.event.EventWithContext)4 EventProcessorConfig (org.graylog.events.processor.EventProcessorConfig)4 Message (org.graylog2.plugin.Message)4 AggregationEventProcessorConfig (org.graylog.events.processor.aggregation.AggregationEventProcessorConfig)3 AggregationSeries (org.graylog.events.processor.aggregation.AggregationSeries)3 JobDefinitionDto (org.graylog.scheduler.JobDefinitionDto)3 JobTriggerDto (org.graylog.scheduler.JobTriggerDto)3 MongoDBFixtures (org.graylog.testing.mongodb.MongoDBFixtures)3 NativeEntityDescriptor (org.graylog2.contentpacks.model.entities.NativeEntityDescriptor)3 ApiOperation (io.swagger.annotations.ApiOperation)2 EventDto (org.graylog.events.event.EventDto)2 ModelId (org.graylog2.contentpacks.model.ModelId)2 EntityDescriptor (org.graylog2.contentpacks.model.entities.EntityDescriptor)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2