use of org.graylog2.plugin.inputs.Extractor.Result 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.inputs.Extractor.Result 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;
}
use of org.graylog2.plugin.inputs.Extractor.Result in project graylog2-server by Graylog2.
the class DashboardsResource method create.
@POST
@Timed
@ApiOperation(value = "Create a dashboard")
@RequiresPermissions(RestPermissions.DASHBOARDS_CREATE)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.DASHBOARD_CREATE)
public Response create(@ApiParam(name = "JSON body", required = true) CreateDashboardRequest cr) throws ValidationException {
// Create dashboard.
final Dashboard dashboard = dashboardService.create(cr.title(), cr.description(), getCurrentUser().getName(), Tools.nowUTC());
final String id = dashboardService.save(dashboard);
final Map<String, String> result = ImmutableMap.of("dashboard_id", id);
final URI dashboardUri = getUriBuilderToSelf().path(DashboardsResource.class, "get").build(id);
return Response.created(dashboardUri).entity(result).build();
}
use of org.graylog2.plugin.inputs.Extractor.Result in project graylog2-server by Graylog2.
the class StreamAlarmCallbackResource method delete.
@DELETE
@Path("/{alarmCallbackId}")
@Timed
@ApiOperation(value = "Delete an alarm callback")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Alarm callback not found."), @ApiResponse(code = 400, message = "Invalid ObjectId.") })
@AuditEvent(type = AuditEventTypes.ALARM_CALLBACK_DELETE)
public void delete(@ApiParam(name = "streamid", value = "The stream id this alarm callback belongs to.", required = true) @PathParam("streamid") String streamid, @ApiParam(name = "alarmCallbackId", required = true) @PathParam("alarmCallbackId") String alarmCallbackId) throws NotFoundException {
checkPermission(RestPermissions.STREAMS_EDIT, streamid);
final Stream stream = streamService.load(streamid);
final AlarmCallbackConfiguration result = alarmCallbackConfigurationService.load(alarmCallbackId);
if (result == null || !result.getStreamId().equals(stream.getId())) {
throw new javax.ws.rs.NotFoundException("Couldn't find alarm callback " + alarmCallbackId + " in for steam " + streamid);
}
if (alarmCallbackConfigurationService.destroy(result) == 0) {
final String msg = "Couldn't remove alarm callback with ID " + result.getId();
LOG.error(msg);
throw new InternalServerErrorException(msg);
}
}
use of org.graylog2.plugin.inputs.Extractor.Result in project graylog2-server by Graylog2.
the class ScrollChunkWriter method writeTo.
@Override
public void writeTo(ScrollResult.ScrollChunk scrollChunk, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
if (LOG.isDebugEnabled()) {
LOG.debug("[{}] Writing chunk {}", Thread.currentThread().getId(), scrollChunk.getChunkNumber());
}
final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
final List<String> fields = scrollChunk.getFields();
final int numberOfFields = fields.size();
if (scrollChunk.isFirstChunk()) {
// write field headers only on first chunk
csvWriter.writeNext(fields.toArray(new String[numberOfFields]));
}
// write result set in same order as the header row
final String[] fieldValues = new String[numberOfFields];
for (ResultMessage message : scrollChunk.getMessages()) {
int idx = 0;
// first collect all values from the current message
for (String fieldName : fields) {
final Object val = message.getMessage().getField(fieldName);
if (val == null) {
fieldValues[idx] = null;
} else {
String stringVal = val.toString();
fieldValues[idx] = stringVal.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
}
idx++;
}
// write the complete line, some fields might not be present in the message, so there might be null values
csvWriter.writeNext(fieldValues);
}
if (csvWriter.checkError()) {
LOG.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
}
csvWriter.close();
}
Aggregations