Search in sources :

Example 6 with AlertCondition

use of org.graylog2.plugin.alarms.AlertCondition in project graylog2-server by Graylog2.

the class StreamFacade method decode.

private NativeEntity<Stream> decode(EntityV1 entity, Map<String, ValueReference> parameters, Map<EntityDescriptor, Object> nativeEntities, User user) {
    final StreamEntity streamEntity = objectMapper.convertValue(entity.data(), StreamEntity.class);
    final CreateStreamRequest createStreamRequest = CreateStreamRequest.create(streamEntity.title().asString(parameters), streamEntity.description().asString(parameters), // ignored
    null, null, streamEntity.matchingType().asString(parameters), streamEntity.removeMatches().asBoolean(parameters), indexSetService.getDefault().id());
    final Stream stream = streamService.create(createStreamRequest, user.getName());
    final List<StreamRule> streamRules = streamEntity.streamRules().stream().map(streamRuleEntity -> createStreamRuleRequest(streamRuleEntity, parameters)).map(request -> streamRuleService.create(DUMMY_STREAM_ID, request)).collect(Collectors.toList());
    // TODO: The creation of legacy alert conditions should be avoided and a new event definition should be created instead
    final List<AlertCondition> alertConditions = streamEntity.alertConditions().stream().map(alertCondition -> createStreamAlertConditionRequest(alertCondition, parameters)).map(request -> {
        try {
            return streamAlertService.fromRequest(request, stream, user.getName());
        } catch (ConfigurationException e) {
            throw new ContentPackException("Couldn't create entity " + entity.toEntityDescriptor(), e);
        }
    }).collect(Collectors.toList());
    // TODO: The creation of legacy alarm callback should be avoided and a new event notification should be created instead
    final List<AlarmCallbackConfiguration> alarmCallbacks = streamEntity.alarmCallbacks().stream().map(alarmCallback -> createStreamAlarmCallbackRequest(alarmCallback, parameters)).map(request -> alarmCallbackConfigurationService.create(stream.getId(), request, user.getName())).collect(Collectors.toList());
    final String savedStreamId;
    try {
        savedStreamId = streamService.saveWithRulesAndOwnership(stream, streamRules, user);
        for (final AlertCondition alertCondition : alertConditions) {
            streamService.addAlertCondition(stream, alertCondition);
        }
        for (final AlarmCallbackConfiguration alarmCallback : alarmCallbacks) {
            alarmCallbackConfigurationService.save(alarmCallback);
        }
    } catch (ValidationException e) {
        throw new ContentPackException("Couldn't create entity " + entity.toEntityDescriptor(), e);
    }
    final Set<ObjectId> outputIds = streamEntity.outputs().stream().map(valueReference -> valueReference.asString(parameters)).map(ModelId::of).map(modelId -> EntityDescriptor.create(modelId, ModelTypes.OUTPUT_V1)).map(descriptor -> findOutput(descriptor, nativeEntities)).map(Output::getId).map(ObjectId::new).collect(Collectors.toSet());
    streamService.addOutputs(new ObjectId(savedStreamId), outputIds);
    if (!alertConditions.isEmpty() || !alarmCallbacks.isEmpty()) {
        // TODO: Remove migration call once we updated the above code to directly create event definitions and notifications
        try {
            legacyAlertsMigration.upgrade();
        } catch (Exception e) {
            LOG.error("Couldn't run migration for newly created legacy alert conditions and/or alarm callbacks", e);
        }
    }
    return NativeEntity.create(entity.id(), savedStreamId, TYPE_V1, stream.getTitle(), stream);
}
Also used : ImmutableGraph(com.google.common.graph.ImmutableGraph) NativeEntity(org.graylog2.contentpacks.model.entities.NativeEntity) LoggerFactory(org.slf4j.LoggerFactory) CreateStreamRuleRequest(org.graylog2.rest.resources.streams.rules.requests.CreateStreamRuleRequest) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) AlertService(org.graylog2.alerts.AlertService) StreamRule(org.graylog2.plugin.streams.StreamRule) ModelType(org.graylog2.contentpacks.model.ModelType) ValueReference(org.graylog2.contentpacks.model.entities.references.ValueReference) StreamRuleService(org.graylog2.streams.StreamRuleService) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) ModelId(org.graylog2.contentpacks.model.ModelId) MutableGraph(com.google.common.graph.MutableGraph) EntityDescriptor(org.graylog2.contentpacks.model.entities.EntityDescriptor) StreamAlarmCallbackEntity(org.graylog2.contentpacks.model.entities.StreamAlarmCallbackEntity) Set(java.util.Set) Collectors(java.util.stream.Collectors) GraphBuilder(com.google.common.graph.GraphBuilder) StreamRuleType(org.graylog2.plugin.streams.StreamRuleType) Objects(java.util.Objects) CreateStreamRequest(org.graylog2.rest.resources.streams.requests.CreateStreamRequest) CreateAlarmCallbackRequest(org.graylog2.rest.models.alarmcallbacks.requests.CreateAlarmCallbackRequest) List(java.util.List) IndexSetService(org.graylog2.indexer.indexset.IndexSetService) UserService(org.graylog2.shared.users.UserService) Stream(org.graylog2.plugin.streams.Stream) StreamService(org.graylog2.streams.StreamService) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) CreateConditionRequest(org.graylog2.rest.models.streams.alerts.requests.CreateConditionRequest) Optional(java.util.Optional) ModelTypes(org.graylog2.contentpacks.model.ModelTypes) EntityDescriptorIds(org.graylog2.contentpacks.EntityDescriptorIds) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) Entity(org.graylog2.contentpacks.model.entities.Entity) ContentPackException(org.graylog2.contentpacks.exceptions.ContentPackException) StreamAlertConditionEntity(org.graylog2.contentpacks.model.entities.StreamAlertConditionEntity) Inject(javax.inject.Inject) ReferenceMapUtils(org.graylog2.contentpacks.model.entities.references.ReferenceMapUtils) V20190722150700_LegacyAlertConditionMigration(org.graylog.events.legacy.V20190722150700_LegacyAlertConditionMigration) EntityExcerpt(org.graylog2.contentpacks.model.entities.EntityExcerpt) ConfigurationException(org.graylog2.plugin.configuration.ConfigurationException) NotFoundException(org.graylog2.database.NotFoundException) Logger(org.slf4j.Logger) StreamEntity(org.graylog2.contentpacks.model.entities.StreamEntity) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StreamRuleEntity(org.graylog2.contentpacks.model.entities.StreamRuleEntity) AlarmCallbackConfigurationService(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationService) EntityV1(org.graylog2.contentpacks.model.entities.EntityV1) Output(org.graylog2.plugin.streams.Output) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) VisibleForTesting(com.google.common.annotations.VisibleForTesting) User(org.graylog2.plugin.database.users.User) NativeEntityDescriptor(org.graylog2.contentpacks.model.entities.NativeEntityDescriptor) Collections(java.util.Collections) Graph(com.google.common.graph.Graph) ContentPackException(org.graylog2.contentpacks.exceptions.ContentPackException) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) StreamRule(org.graylog2.plugin.streams.StreamRule) StreamEntity(org.graylog2.contentpacks.model.entities.StreamEntity) ContentPackException(org.graylog2.contentpacks.exceptions.ContentPackException) ConfigurationException(org.graylog2.plugin.configuration.ConfigurationException) NotFoundException(org.graylog2.database.NotFoundException) ValidationException(org.graylog2.plugin.database.ValidationException) ConfigurationException(org.graylog2.plugin.configuration.ConfigurationException) CreateStreamRequest(org.graylog2.rest.resources.streams.requests.CreateStreamRequest) Output(org.graylog2.plugin.streams.Output) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration)

Example 7 with AlertCondition

use of org.graylog2.plugin.alarms.AlertCondition in project graylog2-server by Graylog2.

the class StreamAlertResource method checkConditions.

@GET
@Timed
@Path("check")
@ApiOperation(value = "Check for triggered alert conditions of this streams. Results cached for " + REST_CHECK_CACHE_SECONDS + " seconds.")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId.") })
public Map<String, Object> checkConditions(@ApiParam(name = "streamId", value = "The ID of the stream to check.", required = true) @PathParam("streamId") String streamId) throws NotFoundException {
    checkPermission(RestPermissions.STREAMS_READ, streamId);
    final Stream stream = streamService.load(streamId);
    final Map<String, Object> result;
    try {
        result = CACHE.get(CACHE_KEY_BASE + stream.getId(), () -> {
            final List<AlertCondition> alertConditions = streamService.getAlertConditions(stream);
            int triggered = 0;
            final List<Map<String, Object>> results = new ArrayList<>(alertConditions.size());
            for (AlertCondition alertCondition : alertConditions) {
                final Map<String, Object> conditionResult = new HashMap<>();
                conditionResult.put("condition", alertCondition);
                final AlertCondition.CheckResult checkResult = alertCondition.runCheck();
                conditionResult.put("triggered", checkResult.isTriggered());
                if (checkResult.isTriggered()) {
                    triggered++;
                    conditionResult.put("alert_description", checkResult.getResultDescription());
                }
                results.add(conditionResult);
            }
            return ImmutableMap.of("results", results, "calculated_at", Tools.getISO8601String(Tools.nowUTC()), "total_triggered", triggered);
        });
    } catch (ExecutionException e) {
        final Throwable rootCause = Throwables.getRootCause(e);
        LOG.error("Could not check for alerts.", rootCause);
        throw new InternalServerErrorException(rootCause);
    }
    return result;
}
Also used : AlertCondition(org.graylog2.plugin.alarms.AlertCondition) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Stream(org.graylog2.plugin.streams.Stream) List(java.util.List) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 8 with AlertCondition

use of org.graylog2.plugin.alarms.AlertCondition in project graylog2-server by Graylog2.

the class AlarmCallbackHistoryServiceImplTest method testSuccess.

@Test
public void testSuccess() throws Exception {
    final AlarmCallbackConfiguration alarmCallbackConfiguration = mockAlarmCallbackConfiguration(new Date());
    final Alert alert = mockAlert();
    final AlertCondition alertCondition = mockAlertCondition();
    final AlarmCallbackHistory alarmCallbackHistory = this.alarmCallbackHistoryService.success(alarmCallbackConfiguration, alert, alertCondition);
    verifyAlarmCallbackHistory(alarmCallbackHistory, alert, alertCondition);
    assertThat(alarmCallbackHistory.result()).isNotNull().isInstanceOf(AlarmCallbackSuccess.class);
    assertThat(alarmCallbackHistory.result().type()).isEqualTo("success");
}
Also used : AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Alert(org.graylog2.alerts.Alert) Date(java.util.Date) MongoDBServiceTest(org.graylog2.database.MongoDBServiceTest) Test(org.junit.Test)

Example 9 with AlertCondition

use of org.graylog2.plugin.alarms.AlertCondition in project graylog2-server by Graylog2.

the class HTTPAlarmCallbackTest method callThrowsAlarmCallbackExceptionIfURLIsMalformed.

@Test
public void callThrowsAlarmCallbackExceptionIfURLIsMalformed() throws Exception {
    final Configuration configuration = new Configuration(ImmutableMap.of("url", "!FOOBAR"));
    alarmCallback.initialize(configuration);
    final Stream stream = new StreamMock(Collections.singletonMap("_id", "stream-id"));
    final AlertCondition alertCondition = new DummyAlertCondition(stream, "alert-id", new DateTime(2017, 3, 29, 12, 0, DateTimeZone.UTC), "user", Collections.emptyMap(), "title");
    final AlertCondition.CheckResult checkResult = new AbstractAlertCondition.CheckResult(true, alertCondition, "Result Description", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC), Collections.emptyList());
    expectedException.expect(AlarmCallbackException.class);
    expectedException.expectMessage("Malformed URL: !FOOBAR");
    alarmCallback.call(stream, checkResult);
}
Also used : StreamMock(org.graylog2.streams.StreamMock) Configuration(org.graylog2.plugin.configuration.Configuration) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Example 10 with AlertCondition

use of org.graylog2.plugin.alarms.AlertCondition in project graylog2-server by Graylog2.

the class HTTPAlarmCallbackTest method callThrowsAlarmCallbackExceptionIfRemoteServerReturnsError.

@Test
public void callThrowsAlarmCallbackExceptionIfRemoteServerReturnsError() throws Exception {
    when(whitelistService.isWhitelisted(anyString())).thenReturn(true);
    server.enqueue(new MockResponse().setResponseCode(500));
    server.start();
    final Configuration configuration = new Configuration(ImmutableMap.of("url", server.url("/").toString()));
    alarmCallback.initialize(configuration);
    alarmCallback.checkConfiguration();
    final Stream stream = new StreamMock(Collections.singletonMap("_id", "stream-id"));
    final AlertCondition alertCondition = new DummyAlertCondition(stream, "alert-id", new DateTime(2017, 3, 29, 12, 0, DateTimeZone.UTC), "user", Collections.emptyMap(), "title");
    final AlertCondition.CheckResult checkResult = new AbstractAlertCondition.CheckResult(true, alertCondition, "Result Description", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC), Collections.emptyList());
    expectedException.expect(AlarmCallbackException.class);
    expectedException.expectMessage("Expected successful HTTP response [2xx] but got [500].");
    alarmCallback.call(stream, checkResult);
    final RecordedRequest request = server.takeRequest();
    assertThat(request.getPath()).isEqualTo("/");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/json");
    assertThat(request.getBodySize()).isPositive();
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) StreamMock(org.graylog2.streams.StreamMock) Configuration(org.graylog2.plugin.configuration.Configuration) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Aggregations

AlertCondition (org.graylog2.plugin.alarms.AlertCondition)45 Stream (org.graylog2.plugin.streams.Stream)35 Test (org.junit.Test)32 ConfigurationException (org.graylog2.plugin.configuration.ConfigurationException)10 DateTime (org.joda.time.DateTime)10 Timed (com.codahale.metrics.annotation.Timed)9 ApiOperation (io.swagger.annotations.ApiOperation)9 AlarmCallbackConfiguration (org.graylog2.alarmcallbacks.AlarmCallbackConfiguration)9 Path (javax.ws.rs.Path)8 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)8 MongoDBServiceTest (org.graylog2.database.MongoDBServiceTest)8 ApiResponses (io.swagger.annotations.ApiResponses)7 AbstractAlertCondition (org.graylog2.alerts.AbstractAlertCondition)7 Date (java.util.Date)6 AuditEvent (org.graylog2.audit.jersey.AuditEvent)6 List (java.util.List)5 POST (javax.ws.rs.POST)5 DummyAlertCondition (org.graylog2.alerts.types.DummyAlertCondition)5 EmailConfiguration (org.graylog2.configuration.EmailConfiguration)5 CreateAlarmCallbackRequest (org.graylog2.rest.models.alarmcallbacks.requests.CreateAlarmCallbackRequest)5