Search in sources :

Example 21 with GrokPattern

use of org.graylog2.grok.GrokPattern in project graylog2-server by Graylog2.

the class GrokResource method bulkUpdatePatternsFromTextFile.

@POST
@Consumes(MediaType.TEXT_PLAIN)
@Timed
@ApiOperation("Add a list of new patterns")
@AuditEvent(type = AuditEventTypes.GROK_PATTERN_IMPORT_CREATE)
public Response bulkUpdatePatternsFromTextFile(@ApiParam(name = "patterns", required = true) @NotNull InputStream patternsFile, @ApiParam(name = "replace", value = "Replace all patterns with the new ones.") @QueryParam("replace") @DefaultValue("false") boolean replace) throws ValidationException, IOException {
    checkPermission(RestPermissions.INPUTS_CREATE);
    final List<GrokPattern> grokPatterns = readGrokPatterns(patternsFile);
    if (!grokPatterns.isEmpty()) {
        final Set<String> updatedPatternNames = Sets.newHashSetWithExpectedSize(grokPatterns.size());
        for (final GrokPattern pattern : grokPatterns) {
            updatedPatternNames.add(pattern.name());
            if (!grokPatternService.validate(pattern)) {
                throw new ValidationException("Invalid pattern " + pattern + ". Did not save any patterns.");
            }
        }
        grokPatternService.saveAll(grokPatterns, replace);
        clusterBus.post(GrokPatternsChangedEvent.create(Collections.emptySet(), updatedPatternNames));
    }
    return Response.accepted().build();
}
Also used : ValidationException(org.graylog2.plugin.database.ValidationException) GrokPattern(org.graylog2.grok.GrokPattern) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent)

Example 22 with GrokPattern

use of org.graylog2.grok.GrokPattern in project graylog2-server by Graylog2.

the class GrokPatternFacade method findExisting.

private Optional<NativeEntity<GrokPattern>> findExisting(EntityV1 entity) {
    final GrokPatternEntity grokPatternEntity = objectMapper.convertValue(entity.data(), GrokPatternEntity.class);
    final String name = grokPatternEntity.name();
    final String pattern = grokPatternEntity.pattern();
    final Optional<GrokPattern> grokPattern = grokPatternService.loadByName(name);
    grokPattern.ifPresent(existingPattern -> compareGrokPatterns(name, pattern, existingPattern.pattern()));
    return grokPattern.map(gp -> NativeEntity.create(entity.id(), gp.id(), TYPE_V1, gp.name(), gp));
}
Also used : GrokPattern(org.graylog2.grok.GrokPattern) GrokPatternEntity(org.graylog2.contentpacks.model.entities.GrokPatternEntity)

Example 23 with GrokPattern

use of org.graylog2.grok.GrokPattern in project graylog2-server by Graylog2.

the class GrokPatternFacade method resolveNativeEntity.

@Override
public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) {
    final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build();
    mutableGraph.addNode(entityDescriptor);
    final ModelId modelId = entityDescriptor.id();
    try {
        final GrokPattern grokPattern = grokPatternService.load(modelId.id());
        final String namedPattern = grokPattern.pattern();
        final Set<String> patterns = GrokPatternService.extractPatternNames(namedPattern);
        patterns.stream().forEach(patternName -> {
            grokPatternService.loadByName(patternName).ifPresent(depPattern -> {
                final EntityDescriptor depEntityDescriptor = EntityDescriptor.create(depPattern.id(), ModelTypes.GROK_PATTERN_V1);
                mutableGraph.putEdge(entityDescriptor, depEntityDescriptor);
            });
        });
    } catch (NotFoundException e) {
        LOG.debug("Couldn't find grok pattern {}", entityDescriptor, e);
    }
    return mutableGraph;
}
Also used : EntityDescriptor(org.graylog2.contentpacks.model.entities.EntityDescriptor) NativeEntityDescriptor(org.graylog2.contentpacks.model.entities.NativeEntityDescriptor) GrokPattern(org.graylog2.grok.GrokPattern) NotFoundException(org.graylog2.database.NotFoundException) ModelId(org.graylog2.contentpacks.model.ModelId)

Example 24 with GrokPattern

use of org.graylog2.grok.GrokPattern in project graylog2-server by Graylog2.

the class MongoDbGrokPatternService method saveAll.

@Override
public List<GrokPattern> saveAll(Collection<GrokPattern> patterns, ImportStrategy importStrategy) throws ValidationException {
    final Map<String, GrokPattern> newPatternsByName;
    try {
        newPatternsByName = patterns.stream().collect(Collectors.toMap(GrokPattern::name, Function.identity()));
    } catch (IllegalStateException e) {
        throw new ValidationException("The supplied Grok patterns contain conflicting names: " + e.getLocalizedMessage());
    }
    final Map<String, GrokPattern> existingPatternsByName = loadAll().stream().collect(Collectors.toMap(GrokPattern::name, Function.identity()));
    if (importStrategy == ABORT_ON_CONFLICT) {
        final Sets.SetView<String> conflictingNames = Sets.intersection(newPatternsByName.keySet(), existingPatternsByName.keySet());
        if (!conflictingNames.isEmpty()) {
            final Iterable<String> limited = Iterables.limit(conflictingNames, MAX_DISPLAYED_CONFLICTS);
            throw new ValidationException("The following Grok patterns already exist: " + StringUtils.join(limited, ", ") + (conflictingNames.size() > MAX_DISPLAYED_CONFLICTS ? " (+ " + (conflictingNames.size() - MAX_DISPLAYED_CONFLICTS) + " more)" : "") + ".");
        }
    }
    try {
        if (!validateAll(patterns)) {
            throw new ValidationException("Invalid patterns");
        }
    } catch (GrokException | PatternSyntaxException e) {
        throw new ValidationException("Invalid patterns.\n" + e.getMessage());
    }
    if (importStrategy == DROP_ALL_EXISTING) {
        deleteAll();
    }
    final List<GrokPattern> savedPatterns = patterns.stream().map(newPattern -> {
        final GrokPattern existingPattern = existingPatternsByName.get(newPattern.name());
        if (existingPattern != null) {
            return newPattern.toBuilder().id(existingPattern.id()).build();
        } else {
            return newPattern;
        }
    }).map(dbCollection::save).map(WriteResult::getSavedObject).collect(Collectors.toList());
    clusterBus.post(GrokPatternsUpdatedEvent.create(newPatternsByName.keySet()));
    return savedPatterns;
}
Also used : Iterables(com.google.common.collect.Iterables) DROP_ALL_EXISTING(org.graylog2.grok.GrokPatternService.ImportStrategy.DROP_ALL_EXISTING) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) WriteResult(org.mongojack.WriteResult) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) Map(java.util.Map) NotFoundException(org.graylog2.database.NotFoundException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) PatternSyntaxException(java.util.regex.PatternSyntaxException) Iterator(java.util.Iterator) GrokException(io.krakens.grok.api.exception.GrokException) DBCursor(org.mongojack.DBCursor) Collection(java.util.Collection) MongoJackObjectMapperProvider(org.graylog2.bindings.providers.MongoJackObjectMapperProvider) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) JacksonDBCollection(org.mongojack.JacksonDBCollection) Set(java.util.Set) DBQuery(org.mongojack.DBQuery) IndexOptions(com.mongodb.client.model.IndexOptions) ABORT_ON_CONFLICT(org.graylog2.grok.GrokPatternService.ImportStrategy.ABORT_ON_CONFLICT) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Indexes(com.mongodb.client.model.Indexes) List(java.util.List) ClusterEventBus(org.graylog2.events.ClusterEventBus) Grok(io.krakens.grok.api.Grok) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) Optional(java.util.Optional) GrokCompiler(io.krakens.grok.api.GrokCompiler) MongoConnection(org.graylog2.database.MongoConnection) ValidationException(org.graylog2.plugin.database.ValidationException) Sets(com.google.common.collect.Sets) GrokException(io.krakens.grok.api.exception.GrokException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 25 with GrokPattern

use of org.graylog2.grok.GrokPattern in project graylog2-server by Graylog2.

the class InMemoryGrokPatternService method saveAll.

@Override
public List<GrokPattern> saveAll(Collection<GrokPattern> patterns, ImportStrategy importStrategy) throws ValidationException {
    if (importStrategy == ABORT_ON_CONFLICT) {
        for (GrokPattern pattern : loadAll()) {
            final boolean patternExists = patterns.stream().anyMatch(p -> p.name().equals(pattern.name()));
            if (patternExists) {
                throw new ValidationException("Grok pattern " + pattern.name() + " already exists");
            }
        }
    }
    try {
        if (!validateAll(patterns)) {
            throw new ValidationException("Patterns invalid.");
        }
    } catch (GrokException | PatternSyntaxException e) {
        throw new ValidationException("Invalid patterns.\n" + e.getMessage());
    }
    if (importStrategy == DROP_ALL_EXISTING) {
        deleteAll();
    }
    final List<GrokPattern> grokPatterns = patterns.stream().map(this::uncheckedSave).collect(Collectors.toList());
    final Set<String> patternNames = grokPatterns.stream().map(GrokPattern::name).collect(Collectors.toSet());
    if (!patternNames.isEmpty()) {
        clusterBus.post(GrokPatternsUpdatedEvent.create(patternNames));
    }
    return grokPatterns;
}
Also used : ValidationException(org.graylog2.plugin.database.ValidationException) GrokException(io.krakens.grok.api.exception.GrokException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

GrokPattern (org.graylog2.grok.GrokPattern)28 Test (org.junit.Test)15 ValidationException (org.graylog2.plugin.database.ValidationException)9 Timed (com.codahale.metrics.annotation.Timed)7 ApiOperation (io.swagger.annotations.ApiOperation)7 NativeEntityDescriptor (org.graylog2.contentpacks.model.entities.NativeEntityDescriptor)7 GrokException (io.krakens.grok.api.exception.GrokException)6 AuditEvent (org.graylog2.audit.jersey.AuditEvent)6 GrokPatternEntity (org.graylog2.contentpacks.model.entities.GrokPatternEntity)6 NotFoundException (org.graylog2.database.NotFoundException)5 PatternSyntaxException (java.util.regex.PatternSyntaxException)4 Response (javax.ws.rs.core.Response)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 Entity (org.graylog2.contentpacks.model.entities.Entity)3 EntityDescriptor (org.graylog2.contentpacks.model.entities.EntityDescriptor)3 Before (org.junit.Before)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Grok (io.krakens.grok.api.Grok)2