Search in sources :

Example 1 with MessageGetStrategy

use of org.apache.metron.common.message.MessageGetStrategy in project metron by apache.

the class ParserBolt method execute.

@SuppressWarnings("unchecked")
@Override
public void execute(Tuple tuple) {
    byte[] originalMessage = (byte[]) messageGetStrategy.get(tuple);
    SensorParserConfig sensorParserConfig = getSensorParserConfig();
    try {
        // we want to ack the tuple in the situation where we have are not doing a bulk write
        // otherwise we want to defer to the writerComponent who will ack on bulk commit.
        boolean ackTuple = !writer.handleAck();
        int numWritten = 0;
        if (sensorParserConfig != null) {
            Map<String, Object> metadata = getMetadata(tuple, sensorParserConfig.getReadMetadata());
            List<FieldValidator> fieldValidations = getConfigurations().getFieldValidations();
            Optional<List<JSONObject>> messages = parser.parseOptional(originalMessage);
            for (JSONObject message : messages.orElse(Collections.emptyList())) {
                message.put(Constants.SENSOR_TYPE, getSensorType());
                if (sensorParserConfig.getMergeMetadata()) {
                    message.putAll(metadata);
                }
                for (FieldTransformer handler : sensorParserConfig.getFieldTransformations()) {
                    if (handler != null) {
                        if (!sensorParserConfig.getMergeMetadata()) {
                            // if we haven't merged metadata, then we need to pass them along as configuration params.
                            handler.transformAndUpdate(message, stellarContext, sensorParserConfig.getParserConfig(), metadata);
                        } else {
                            handler.transformAndUpdate(message, stellarContext, sensorParserConfig.getParserConfig());
                        }
                    }
                }
                if (!message.containsKey(Constants.GUID)) {
                    message.put(Constants.GUID, UUID.randomUUID().toString());
                }
                if (parser.validate(message) && (filter == null || filter.emitTuple(message, stellarContext))) {
                    numWritten++;
                    List<FieldValidator> failedValidators = getFailedValidators(message, fieldValidations);
                    if (failedValidators.size() > 0) {
                        MetronError error = new MetronError().withErrorType(Constants.ErrorType.PARSER_INVALID).withSensorType(getSensorType()).addRawMessage(message);
                        Set<String> errorFields = failedValidators.stream().flatMap(fieldValidator -> fieldValidator.getInput().stream()).collect(Collectors.toSet());
                        if (!errorFields.isEmpty()) {
                            error.withErrorFields(errorFields);
                        }
                        ErrorUtils.handleError(collector, error);
                    } else {
                        writer.write(getSensorType(), tuple, message, getConfigurations(), messageGetStrategy);
                    }
                }
            }
        }
        // then we want to handle the ack ourselves.
        if (ackTuple || numWritten == 0) {
            collector.ack(tuple);
        }
    } catch (Throwable ex) {
        handleError(originalMessage, tuple, ex, collector);
    }
}
Also used : OutputFieldsDeclarer(org.apache.storm.topology.OutputFieldsDeclarer) TopologyContext(org.apache.storm.task.TopologyContext) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) METADATA_PREFIX(org.apache.metron.common.Constants.METADATA_PREFIX) StringUtils(org.apache.commons.lang3.StringUtils) Filters(org.apache.metron.parsers.filters.Filters) MessageParser(org.apache.metron.parsers.interfaces.MessageParser) ArrayList(java.util.ArrayList) Tuple(org.apache.storm.tuple.Tuple) OutputCollector(org.apache.storm.task.OutputCollector) Map(java.util.Map) SensorParserConfig(org.apache.metron.common.configuration.SensorParserConfig) JSONUtils(org.apache.metron.common.utils.JSONUtils) MessageGetStrategy(org.apache.metron.common.message.MessageGetStrategy) ConfiguredParserBolt(org.apache.metron.common.bolt.ConfiguredParserBolt) FieldValidator(org.apache.metron.common.configuration.FieldValidator) ErrorUtils(org.apache.metron.common.utils.ErrorUtils) MetronError(org.apache.metron.common.error.MetronError) Context(org.apache.metron.stellar.dsl.Context) FieldTransformer(org.apache.metron.common.configuration.FieldTransformer) Logger(org.slf4j.Logger) MethodHandles(java.lang.invoke.MethodHandles) Set(java.util.Set) IOException(java.io.IOException) UUID(java.util.UUID) Fields(org.apache.storm.tuple.Fields) Constants(org.apache.metron.common.Constants) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) List(java.util.List) JSONObject(org.json.simple.JSONObject) MessageGetters(org.apache.metron.common.message.MessageGetters) MessageFilter(org.apache.metron.parsers.interfaces.MessageFilter) StellarFunctions(org.apache.metron.stellar.dsl.StellarFunctions) Optional(java.util.Optional) Collections(java.util.Collections) MetronError(org.apache.metron.common.error.MetronError) FieldValidator(org.apache.metron.common.configuration.FieldValidator) SensorParserConfig(org.apache.metron.common.configuration.SensorParserConfig) JSONObject(org.json.simple.JSONObject) FieldTransformer(org.apache.metron.common.configuration.FieldTransformer) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with MessageGetStrategy

use of org.apache.metron.common.message.MessageGetStrategy in project metron by apache.

the class EnrichmentJoinBoltTest method test.

@Test
public void test() throws IOException {
    EnrichmentJoinBolt enrichmentJoinBolt = new EnrichmentJoinBolt("zookeeperUrl");
    enrichmentJoinBolt.setCuratorFramework(client);
    enrichmentJoinBolt.setZKCache(cache);
    enrichmentJoinBolt.getConfigurations().updateSensorEnrichmentConfig(sensorType, new FileInputStream(sampleSensorEnrichmentConfigPath));
    enrichmentJoinBolt.withMaxCacheSize(100);
    enrichmentJoinBolt.withMaxTimeRetain(10000);
    enrichmentJoinBolt.prepare(new HashMap<>(), topologyContext, outputCollector);
    Set<String> actualStreamIds = enrichmentJoinBolt.getStreamIds(sampleMessage);
    Assert.assertEquals(joinStreamIds, actualStreamIds);
    Map<String, Tuple> streamMessageMap = new HashMap<>();
    MessageGetStrategy messageGetStrategy = mock(MessageGetStrategy.class);
    Tuple sampleTuple = mock(Tuple.class);
    when(messageGetStrategy.get(sampleTuple)).thenReturn(sampleMessage);
    Tuple enrichedTuple = mock(Tuple.class);
    when(messageGetStrategy.get(enrichedTuple)).thenReturn(enrichedMessage);
    streamMessageMap.put("message", sampleTuple);
    streamMessageMap.put("enriched", enrichedTuple);
    JSONObject joinedMessage = enrichmentJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    removeTimingFields(joinedMessage);
    Assert.assertEquals(expectedJoinedMessage, joinedMessage);
}
Also used : JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) MessageGetStrategy(org.apache.metron.common.message.MessageGetStrategy) FileInputStream(java.io.FileInputStream) Tuple(org.apache.storm.tuple.Tuple) Test(org.junit.Test) BaseEnrichmentBoltTest(org.apache.metron.test.bolt.BaseEnrichmentBoltTest)

Example 3 with MessageGetStrategy

use of org.apache.metron.common.message.MessageGetStrategy in project metron by apache.

the class ThreatIntelJoinBoltTest method test.

public void test(String threatTriageConfig, boolean badConfig) throws IOException {
    ThreatIntelJoinBolt threatIntelJoinBolt = new ThreatIntelJoinBolt("zookeeperUrl");
    threatIntelJoinBolt.setCuratorFramework(client);
    threatIntelJoinBolt.setZKCache(cache);
    SensorEnrichmentConfig enrichmentConfig = JSONUtils.INSTANCE.load(new FileInputStream(sampleSensorEnrichmentConfigPath), SensorEnrichmentConfig.class);
    boolean withThreatTriage = threatTriageConfig != null;
    if (withThreatTriage) {
        try {
            enrichmentConfig.getThreatIntel().setTriageConfig(JSONUtils.INSTANCE.load(threatTriageConfig, ThreatTriageConfig.class));
            if (badConfig) {
                Assert.fail(threatTriageConfig + "\nThis should not parse!");
            }
        } catch (JsonMappingException pe) {
            if (!badConfig) {
                throw pe;
            }
        }
    }
    threatIntelJoinBolt.getConfigurations().updateSensorEnrichmentConfig(sensorType, enrichmentConfig);
    HashMap<String, Object> globalConfig = new HashMap<>();
    String baseDir = UnitTestHelper.findDir("GeoLite");
    File geoHdfsFile = new File(new File(baseDir), "GeoIP2-City-Test.mmdb.gz");
    globalConfig.put(GeoLiteDatabase.GEO_HDFS_FILE, geoHdfsFile.getAbsolutePath());
    threatIntelJoinBolt.getConfigurations().updateGlobalConfig(globalConfig);
    threatIntelJoinBolt.withMaxCacheSize(100);
    threatIntelJoinBolt.withMaxTimeRetain(10000);
    threatIntelJoinBolt.prepare(new HashMap<>(), topologyContext, outputCollector);
    Map<String, Object> fieldMap = threatIntelJoinBolt.getFieldMap("incorrectSourceType");
    Assert.assertNull(fieldMap);
    fieldMap = threatIntelJoinBolt.getFieldMap(sensorType);
    Assert.assertTrue(fieldMap.containsKey("hbaseThreatIntel"));
    MessageGetStrategy messageGetStrategy = mock(MessageGetStrategy.class);
    Tuple messageTuple = mock(Tuple.class);
    when(messageGetStrategy.get(messageTuple)).thenReturn(message);
    Map<String, Tuple> streamMessageMap = new HashMap<>();
    streamMessageMap.put("message", messageTuple);
    JSONObject joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertFalse(joinedMessage.containsKey("is_alert"));
    when(messageGetStrategy.get(messageTuple)).thenReturn(messageWithTiming);
    joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertFalse(joinedMessage.containsKey("is_alert"));
    when(messageGetStrategy.get(messageTuple)).thenReturn(alertMessage);
    joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertTrue(joinedMessage.containsKey("is_alert") && "true".equals(joinedMessage.get("is_alert")));
    if (withThreatTriage && !badConfig) {
        assertTrue(joinedMessage.containsKey("threat.triage.score"));
        Double score = (Double) joinedMessage.get("threat.triage.score");
        assertTrue(Math.abs(10d - score) < 1e-10);
    } else {
        assertFalse(joinedMessage.containsKey("threat.triage.score"));
    }
}
Also used : ThreatTriageConfig(org.apache.metron.common.configuration.enrichment.threatintel.ThreatTriageConfig) HashMap(java.util.HashMap) MessageGetStrategy(org.apache.metron.common.message.MessageGetStrategy) FileInputStream(java.io.FileInputStream) JSONObject(org.json.simple.JSONObject) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JSONObject(org.json.simple.JSONObject) File(java.io.File) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) Tuple(org.apache.storm.tuple.Tuple)

Aggregations

HashMap (java.util.HashMap)3 MessageGetStrategy (org.apache.metron.common.message.MessageGetStrategy)3 Tuple (org.apache.storm.tuple.Tuple)3 JSONObject (org.json.simple.JSONObject)3 FileInputStream (java.io.FileInputStream)2 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 File (java.io.File)1 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 MethodHandles (java.lang.invoke.MethodHandles)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Set (java.util.Set)1 UUID (java.util.UUID)1 Collectors (java.util.stream.Collectors)1 StringUtils (org.apache.commons.lang3.StringUtils)1 Constants (org.apache.metron.common.Constants)1