Search in sources :

Example 51 with Notification

use of org.graylog2.notifications.Notification in project graylog2-server by Graylog2.

the class AggregationEventProcessor method eventsFromAggregationResult.

@VisibleForTesting
ImmutableList<EventWithContext> eventsFromAggregationResult(EventFactory eventFactory, AggregationEventProcessorParameters parameters, AggregationResult result) {
    final ImmutableList.Builder<EventWithContext> eventsWithContext = ImmutableList.builder();
    final Set<String> sourceStreams = buildEventSourceStreams(getStreams(parameters), result.sourceStreams());
    for (final AggregationKeyResult keyResult : result.keyResults()) {
        if (!satisfiesConditions(keyResult)) {
            LOG.debug("Skipping result <{}> because the conditions <{}> don't match", keyResult, config.conditions());
            continue;
        }
        final String keyString = Strings.join(keyResult.key(), '|');
        final String eventMessage = createEventMessageString(keyString, keyResult);
        // Extract eventTime from the key result or use query time range as fallback
        final DateTime eventTime = keyResult.timestamp().orElse(result.effectiveTimerange().to());
        final Event event = eventFactory.createEvent(eventDefinition, eventTime, eventMessage);
        // TODO: Do we have to set any other event fields here?
        event.setTimerangeStart(parameters.timerange().getFrom());
        event.setTimerangeEnd(parameters.timerange().getTo());
        sourceStreams.forEach(event::addSourceStream);
        final Map<String, Object> fields = new HashMap<>();
        // username=jane
        for (int i = 0; i < config.groupBy().size(); i++) {
            fields.put(config.groupBy().get(i), keyResult.key().get(i));
        }
        // Group By fields need to be saved on the event so they are available to the subsequent notification events
        event.setGroupByFields(fields.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())));
        // aggregation_value_card_anonid=23
        for (AggregationSeriesValue seriesValue : keyResult.seriesValues()) {
            final String function = seriesValue.series().function().toString().toLowerCase(Locale.ROOT);
            final Optional<String> field = seriesValue.series().field();
            final String fieldName;
            if (field.isPresent()) {
                fieldName = String.format(Locale.ROOT, "aggregation_value_%s_%s", function, field.get());
            } else {
                fieldName = String.format(Locale.ROOT, "aggregation_value_%s", function);
            }
            fields.put(fieldName, seriesValue.value());
        }
        // This is the concatenated key value
        fields.put("aggregation_key", keyString);
        // TODO: Can we find a useful source value?
        final Message message = new Message(eventMessage, "", result.effectiveTimerange().to());
        message.addFields(fields);
        LOG.debug("Creating event {}/{} - {} {} ({})", eventDefinition.title(), eventDefinition.id(), keyResult.key(), seriesString(keyResult), fields);
        eventsWithContext.add(EventWithContext.create(event, message));
    }
    return eventsWithContext.build();
}
Also used : ResultMessage(org.graylog2.indexer.results.ResultMessage) Message(org.graylog2.plugin.Message) HashMap(java.util.HashMap) ImmutableList(com.google.common.collect.ImmutableList) EventWithContext(org.graylog.events.event.EventWithContext) ElasticsearchQueryString(org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString) DateTime(org.joda.time.DateTime) Event(org.graylog.events.event.Event) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 52 with Notification

use of org.graylog2.notifications.Notification in project graylog2-server by Graylog2.

the class EventNotificationsResource method listNotifications.

@GET
@ApiOperation("List all available notifications")
public PaginatedResponse<NotificationDto> listNotifications(@ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "query") @QueryParam("query") @DefaultValue("") String query) {
    final SearchQuery searchQuery = searchQueryParser.parse(query);
    final PaginatedList<NotificationDto> result = dbNotificationService.searchPaginated(searchQuery, notification -> {
        return isPermitted(RestPermissions.EVENT_NOTIFICATIONS_READ, notification.id());
    }, "title", page, perPage);
    return PaginatedResponse.create("notifications", result, query);
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) NotificationDto(org.graylog.events.notifications.NotificationDto) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 53 with Notification

use of org.graylog2.notifications.Notification in project graylog2-server by Graylog2.

the class EventNotificationsResource method test.

@POST
@Timed
@Path("/test")
@RequiresPermissions(RestPermissions.EVENT_NOTIFICATIONS_CREATE)
@ApiOperation(value = "Send a test alert for a given event notification")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Event notification is invalid."), @ApiResponse(code = 500, message = "Error while testing event notification") })
@NoAuditEvent("only used to test event notifications")
public Response test(@ApiParam(name = "JSON Body") NotificationDto dto) {
    checkPermission(RestPermissions.EVENT_NOTIFICATIONS_CREATE);
    final ValidationResult validationResult = dto.validate();
    if (validationResult.failed()) {
        return Response.status(Response.Status.BAD_REQUEST).entity(validationResult).build();
    }
    resourceHandler.test(dto, getSubject().getPrincipal().toString());
    return Response.ok().build();
}
Also used : ValidationResult(org.graylog2.plugin.rest.ValidationResult) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 54 with Notification

use of org.graylog2.notifications.Notification in project graylog2-server by Graylog2.

the class EventNotificationsResource method update.

@PUT
@Path("/{notificationId}")
@ApiOperation("Update existing notification")
@AuditEvent(type = EventsAuditEventTypes.EVENT_NOTIFICATION_UPDATE)
public Response update(@ApiParam(name = "notificationId") @PathParam("notificationId") @NotBlank String notificationId, @ApiParam(name = "JSON Body") NotificationDto dto) {
    checkPermission(RestPermissions.EVENT_NOTIFICATIONS_EDIT, notificationId);
    dbNotificationService.get(notificationId).orElseThrow(() -> new NotFoundException("Notification " + notificationId + " doesn't exist"));
    if (!notificationId.equals(dto.id())) {
        throw new BadRequestException("Notification IDs don't match");
    }
    final ValidationResult validationResult = dto.validate();
    if (validationResult.failed()) {
        return Response.status(Response.Status.BAD_REQUEST).entity(validationResult).build();
    }
    return Response.ok().entity(resourceHandler.update(dto)).build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) BadRequestException(javax.ws.rs.BadRequestException) ValidationResult(org.graylog2.plugin.rest.ValidationResult) Path(javax.ws.rs.Path) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) PUT(javax.ws.rs.PUT)

Example 55 with Notification

use of org.graylog2.notifications.Notification in project graylog2-server by Graylog2.

the class EventNotificationsResource method test.

@POST
@Timed
@Path("/{notificationId}/test")
@ApiOperation(value = "Send a test alert for a given event notification")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Event notification not found."), @ApiResponse(code = 500, message = "Error while testing event notification") })
@NoAuditEvent("only used to test event notifications")
public Response test(@ApiParam(name = "notificationId", value = "The event notification id to send a test alert for.", required = true) @PathParam("notificationId") @NotBlank String notificationId) {
    checkPermission(RestPermissions.EVENT_NOTIFICATIONS_EDIT, notificationId);
    final NotificationDto notificationDto = dbNotificationService.get(notificationId).orElseThrow(() -> new NotFoundException("Notification " + notificationId + " doesn't exist"));
    resourceHandler.test(notificationDto, getSubject().getPrincipal().toString());
    return Response.ok().build();
}
Also used : NotificationDto(org.graylog.events.notifications.NotificationDto) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Aggregations

Notification (org.graylog2.notifications.Notification)28 Test (org.junit.Test)7 ImmutableList (com.google.common.collect.ImmutableList)6 ApiOperation (io.swagger.annotations.ApiOperation)6 NotificationDto (org.graylog.events.notifications.NotificationDto)6 Map (java.util.Map)5 EventDefinitionDto (org.graylog.events.processor.EventDefinitionDto)5 AlertCondition (org.graylog2.plugin.alarms.AlertCondition)5 Activity (org.graylog2.shared.system.activities.Activity)5 Timed (com.codahale.metrics.annotation.Timed)4 List (java.util.List)4 Path (javax.ws.rs.Path)4 JobDefinitionDto (org.graylog.scheduler.JobDefinitionDto)4 EntityV1 (org.graylog2.contentpacks.model.entities.EntityV1)4 NotFoundException (org.graylog2.database.NotFoundException)4 MessageSummary (org.graylog2.plugin.MessageSummary)4 TransportConfigurationException (org.graylog2.plugin.alarms.transports.TransportConfigurationException)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 ApiResponses (io.swagger.annotations.ApiResponses)3