use of org.graylog2.plugin.alarms.callbacks.AlarmCallback in project graylog2-server by Graylog2.
the class StreamResource method cloneStream.
@POST
@Path("/{streamId}/clone")
@Timed
@ApiOperation(value = "Clone a stream")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid or missing Stream id.") })
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.STREAM_CREATE)
public Response cloneStream(@ApiParam(name = "streamId", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CloneStreamRequest cr) throws ValidationException, NotFoundException {
checkPermission(RestPermissions.STREAMS_CREATE);
checkPermission(RestPermissions.STREAMS_READ, streamId);
checkNotDefaultStream(streamId, "The default stream cannot be cloned.");
final Stream sourceStream = streamService.load(streamId);
final String creatorUser = getCurrentUser().getName();
// Create stream.
final Map<String, Object> streamData = Maps.newHashMap();
streamData.put(StreamImpl.FIELD_TITLE, cr.title());
streamData.put(StreamImpl.FIELD_DESCRIPTION, cr.description());
streamData.put(StreamImpl.FIELD_CREATOR_USER_ID, creatorUser);
streamData.put(StreamImpl.FIELD_CREATED_AT, Tools.nowUTC());
streamData.put(StreamImpl.FIELD_MATCHING_TYPE, sourceStream.getMatchingType().toString());
streamData.put(StreamImpl.FIELD_REMOVE_MATCHES_FROM_DEFAULT_STREAM, cr.removeMatchesFromDefaultStream());
streamData.put(StreamImpl.FIELD_INDEX_SET_ID, cr.indexSetId());
final Stream stream = streamService.create(streamData);
streamService.pause(stream);
final String id = streamService.save(stream);
final List<StreamRule> sourceStreamRules = streamRuleService.loadForStream(sourceStream);
for (StreamRule streamRule : sourceStreamRules) {
final Map<String, Object> streamRuleData = Maps.newHashMapWithExpectedSize(6);
streamRuleData.put(StreamRuleImpl.FIELD_TYPE, streamRule.getType().toInteger());
streamRuleData.put(StreamRuleImpl.FIELD_FIELD, streamRule.getField());
streamRuleData.put(StreamRuleImpl.FIELD_VALUE, streamRule.getValue());
streamRuleData.put(StreamRuleImpl.FIELD_INVERTED, streamRule.getInverted());
streamRuleData.put(StreamRuleImpl.FIELD_STREAM_ID, new ObjectId(id));
streamRuleData.put(StreamRuleImpl.FIELD_DESCRIPTION, streamRule.getDescription());
final StreamRule newStreamRule = streamRuleService.create(streamRuleData);
streamRuleService.save(newStreamRule);
}
for (AlertCondition alertCondition : streamService.getAlertConditions(sourceStream)) {
try {
final AlertCondition clonedAlertCondition = alertService.fromRequest(CreateConditionRequest.create(alertCondition.getType(), alertCondition.getTitle(), alertCondition.getParameters()), stream, creatorUser);
streamService.addAlertCondition(stream, clonedAlertCondition);
} catch (ConfigurationException e) {
LOG.warn("Unable to clone alert condition <" + alertCondition + "> - skipping: ", e);
}
}
for (AlarmCallbackConfiguration alarmCallbackConfiguration : alarmCallbackConfigurationService.getForStream(sourceStream)) {
final CreateAlarmCallbackRequest request = CreateAlarmCallbackRequest.create(alarmCallbackConfiguration);
final AlarmCallbackConfiguration alarmCallback = alarmCallbackConfigurationService.create(stream.getId(), request, getCurrentUser().getName());
alarmCallbackConfigurationService.save(alarmCallback);
}
for (Output output : sourceStream.getOutputs()) {
streamService.addOutput(stream, output);
}
clusterEventBus.post(StreamsChangedEvent.create(stream.getId()));
final Map<String, String> result = ImmutableMap.of("stream_id", id);
final URI streamUri = getUriBuilderToSelf().path(StreamResource.class).path("{streamId}").build(id);
return Response.created(streamUri).entity(result).build();
}
use of org.graylog2.plugin.alarms.callbacks.AlarmCallback in project graylog2-server by Graylog2.
the class StreamAlertResource method sendDummyAlert.
@POST
@Timed
@Path("sendDummyAlert")
@ApiOperation(value = "Send a test mail for a given stream")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId."), @ApiResponse(code = 400, message = "Stream has no alarm callbacks") })
@NoAuditEvent("only used to test alert emails")
public void sendDummyAlert(@ApiParam(name = "streamId", value = "The stream id the test alert should be sent for.", required = true) @PathParam("streamId") String streamId) throws TransportConfigurationException, EmailException, NotFoundException {
checkPermission(RestPermissions.STREAMS_EDIT, streamId);
final Stream stream = streamService.load(streamId);
final DummyAlertCondition dummyAlertCondition = new DummyAlertCondition(stream, null, Tools.nowUTC(), getSubject().getPrincipal().toString(), Collections.emptyMap(), "Test Alert");
try {
AbstractAlertCondition.CheckResult checkResult = dummyAlertCondition.runCheck();
List<AlarmCallbackConfiguration> callConfigurations = alarmCallbackConfigurationService.getForStream(stream);
if (callConfigurations.size() == 0) {
final String message = "Stream has no alarm callbacks, cannot send test alert.";
LOG.warn(message);
throw new BadRequestException(message);
}
for (AlarmCallbackConfiguration configuration : callConfigurations) {
AlarmCallback alarmCallback = alarmCallbackFactory.create(configuration);
alarmCallback.call(stream, checkResult);
}
} catch (AlarmCallbackException | ClassNotFoundException | AlarmCallbackConfigurationException e) {
throw new InternalServerErrorException(e.getMessage(), e);
}
}
use of org.graylog2.plugin.alarms.callbacks.AlarmCallback in project graylog2-server by Graylog2.
the class StreamAlarmCallbackResource method convertConfigurationValues.
private Map<String, Object> convertConfigurationValues(final CreateAlarmCallbackRequest alarmCallbackRequest) {
final ConfigurationRequest requestedConfiguration;
try {
final AlarmCallback alarmCallback = alarmCallbackFactory.create(alarmCallbackRequest.type());
requestedConfiguration = alarmCallback.getRequestedConfiguration();
} catch (ClassNotFoundException e) {
throw new BadRequestException("Unable to load alarm callback of type " + alarmCallbackRequest.type(), e);
}
// coerce the configuration to their correct types according to the alarmcallback's requested config
final Map<String, Object> configuration;
try {
configuration = ConfigurationMapConverter.convertValues(alarmCallbackRequest.configuration(), requestedConfiguration);
} catch (ValidationException e) {
throw new BadRequestException("Invalid configuration map", e);
}
return configuration;
}
use of org.graylog2.plugin.alarms.callbacks.AlarmCallback in project graylog2-server by Graylog2.
the class AlarmCallbacksResource method available.
@GET
@Path("/types")
@Timed
@ApiOperation(value = "Get a list of all alarm callbacks types")
public AvailableAlarmCallbacksResponse available() {
final Map<String, AvailableAlarmCallbackSummaryResponse> types = Maps.newHashMapWithExpectedSize(availableAlarmCallbacks.size());
for (AlarmCallback availableAlarmCallback : availableAlarmCallbacks) {
final AvailableAlarmCallbackSummaryResponse type = new AvailableAlarmCallbackSummaryResponse();
type.name = availableAlarmCallback.getName();
type.requested_configuration = getConfigurationRequest(availableAlarmCallback).asList();
types.put(availableAlarmCallback.getClass().getCanonicalName(), type);
}
final AvailableAlarmCallbacksResponse response = new AvailableAlarmCallbacksResponse();
response.types = types;
return response;
}
use of org.graylog2.plugin.alarms.callbacks.AlarmCallback in project graylog2-server by Graylog2.
the class V20161125161400_AlertReceiversMigrationTest method doMigrateSingleQualifyingStream.
@Test
public void doMigrateSingleQualifyingStream() throws Exception {
final String matchingStreamId = new ObjectId().toHexString();
final Stream stream1 = mock(Stream.class);
when(stream1.getAlertReceivers()).thenReturn(Collections.emptyMap());
final Stream stream2 = mock(Stream.class);
when(stream2.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser"), "emails", ImmutableList.of("foo@bar.com")));
when(stream2.getId()).thenReturn(matchingStreamId);
when(this.streamService.loadAll()).thenReturn(ImmutableList.of(stream1, stream2));
final AlertCondition alertCondition = mock(AlertCondition.class);
when(this.streamService.getAlertConditions(eq(stream2))).thenReturn(ImmutableList.of(alertCondition));
final String alarmCallbackId = new ObjectId().toHexString();
final AlarmCallbackConfiguration alarmCallback = AlarmCallbackConfigurationImpl.create(alarmCallbackId, matchingStreamId, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
when(alarmCallbackConfigurationService.getForStream(eq(stream2))).thenReturn(ImmutableList.of(alarmCallback));
when(alarmCallbackConfigurationService.save(eq(alarmCallback))).thenReturn(alarmCallbackId);
when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId));
this.alertReceiversMigration.upgrade();
final ArgumentCaptor<AlarmCallbackConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(AlarmCallbackConfiguration.class);
verify(this.alarmCallbackConfigurationService, times(1)).save(configurationArgumentCaptor.capture());
final AlarmCallbackConfiguration updatedConfiguration = configurationArgumentCaptor.getValue();
assertThat(updatedConfiguration).isEqualTo(alarmCallback);
assertThat(updatedConfiguration.getType()).isEqualTo(EmailAlarmCallback.class.getCanonicalName());
assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).size()).isEqualTo(1);
assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).get(0)).isEqualTo("foo@bar.com");
assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser");
final ArgumentCaptor<BasicDBObject> queryCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
final ArgumentCaptor<BasicDBObject> updateCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
verify(this.dbCollection, times(1)).update(queryCaptor.capture(), updateCaptor.capture());
assertThat(queryCaptor.getValue().toJson()).isEqualTo("{ \"_id\" : { \"$oid\" : \"" + matchingStreamId + "\" } }");
assertThat(updateCaptor.getValue().toJson()).isEqualTo("{ \"$unset\" : { \"" + StreamImpl.FIELD_ALERT_RECEIVERS + "\" : \"\" } }");
verifyMigrationCompletedWasPosted(ImmutableMap.of(matchingStreamId, Optional.of(alarmCallbackId)));
}
Aggregations