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);
}
}
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();
}
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;
}
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();
}
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);
});
}
Aggregations