Search in sources :

Example 21 with SensorEnrichmentConfig

use of org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig in project metron by apache.

the class UnifiedEnrichmentBolt method execute.

/**
 * Fully enrich a message based on the strategy which was used to configure the bolt.
 * Each enrichment is done in parallel and the results are joined together.  Each enrichment
 * will use a cache so computation is avoided if the result has been computed before.
 *
 * Errors in the enrichment result in an error message being sent on the "error" stream.
 * The successful enrichments will be joined with the original message and the message will
 * be sent along the "message" stream.
 *
 * @param input The input tuple to be processed.
 */
@Override
public void execute(Tuple input) {
    JSONObject message = generateMessage(input);
    try {
        String sourceType = MessageUtils.getSensorType(message);
        SensorEnrichmentConfig config = getConfigurations().getSensorEnrichmentConfig(sourceType);
        if (config == null) {
            LOG.debug("Unable to find SensorEnrichmentConfig for sourceType: {}", sourceType);
            config = new SensorEnrichmentConfig();
        }
        // This is an existing kludge for the stellar adapter to pass information along.
        // We should figure out if this can be rearchitected a bit.  This smells.
        config.getConfiguration().putIfAbsent(STELLAR_CONTEXT_CONF, stellarContext);
        String guid = getGUID(input, message);
        // enrich the message
        ParallelEnricher.EnrichmentResult result = enricher.apply(message, strategy, config, perfLog);
        JSONObject enriched = result.getResult();
        enriched = strategy.postProcess(enriched, config, enrichmentContext);
        // we can emit the message now
        collector.emit("message", input, new Values(guid, enriched));
        // and handle each of the errors in turn.  If any adapter errored out, we will have one message per.
        for (Map.Entry<Object, Throwable> t : result.getEnrichmentErrors()) {
            LOG.error("[Metron] Unable to enrich message: {}", message, t);
            MetronError error = new MetronError().withErrorType(strategy.getErrorType()).withMessage(t.getValue().getMessage()).withThrowable(t.getValue()).addRawMessage(t.getKey());
            ErrorUtils.handleError(collector, error);
        }
    } catch (Exception e) {
        // If something terrible and unexpected happens then we want to send an error along, but this
        // really shouldn't be happening.
        LOG.error("[Metron] Unable to enrich message: {}", message, e);
        MetronError error = new MetronError().withErrorType(strategy.getErrorType()).withMessage(e.getMessage()).withThrowable(e).addRawMessage(message);
        ErrorUtils.handleError(collector, error);
    } finally {
        collector.ack(input);
    }
}
Also used : JSONObject(org.json.simple.JSONObject) MetronError(org.apache.metron.common.error.MetronError) Values(org.apache.storm.tuple.Values) JSONObject(org.json.simple.JSONObject) ParallelEnricher(org.apache.metron.enrichment.parallel.ParallelEnricher) HashMap(java.util.HashMap) Map(java.util.Map) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig)

Example 22 with SensorEnrichmentConfig

use of org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig in project metron by apache.

the class SimpleHBaseAdapterTest method testMultiColumnFamilies.

@Test
public void testMultiColumnFamilies() throws Exception {
    SimpleHBaseAdapter sha = new SimpleHBaseAdapter();
    sha.lookup = lookup;
    SensorEnrichmentConfig broSc = JSONUtils.INSTANCE.load(sourceConfigWithCFStr, SensorEnrichmentConfig.class);
    JSONObject actualMessage = sha.enrich(new CacheKey("test", "test", broSc));
    Assert.assertEquals(actualMessage, new JSONObject());
    actualMessage = sha.enrich(new CacheKey("ip_dst_addr", "10.0.2.4", broSc));
    Assert.assertNotNull(actualMessage);
    Assert.assertEquals(new JSONObject(ImmutableMap.of("cf1.key", "value")), actualMessage);
}
Also used : JSONObject(org.json.simple.JSONObject) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) CacheKey(org.apache.metron.enrichment.bolt.CacheKey) Test(org.junit.Test)

Example 23 with SensorEnrichmentConfig

use of org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig in project metron by apache.

the class SimpleHBaseAdapterTest method testEnrichNonStringValue.

@Test
public void testEnrichNonStringValue() throws Exception {
    SimpleHBaseAdapter sha = new SimpleHBaseAdapter();
    sha.lookup = lookup;
    SensorEnrichmentConfig broSc = JSONUtils.INSTANCE.load(sourceConfigStr, SensorEnrichmentConfig.class);
    JSONObject actualMessage = sha.enrich(new CacheKey("test", "test", broSc));
    Assert.assertEquals(actualMessage, new JSONObject());
    actualMessage = sha.enrich(new CacheKey("ip_dst_addr", 10L, broSc));
    Assert.assertEquals(actualMessage, new JSONObject());
}
Also used : JSONObject(org.json.simple.JSONObject) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) CacheKey(org.apache.metron.enrichment.bolt.CacheKey) Test(org.junit.Test)

Example 24 with SensorEnrichmentConfig

use of org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig in project metron by apache.

the class ThreatIntelAdapterTest method testEnrichNonString.

@Test
public void testEnrichNonString() throws Exception {
    ThreatIntelAdapter tia = new ThreatIntelAdapter();
    tia.lookup = lookup;
    SensorEnrichmentConfig broSc = JSONUtils.INSTANCE.load(sourceConfigStr, SensorEnrichmentConfig.class);
    JSONObject actualMessage = tia.enrich(new CacheKey("ip_dst_addr", "10.0.2.3", broSc));
    Assert.assertNotNull(actualMessage);
    Assert.assertEquals(expectedMessage, actualMessage);
    actualMessage = tia.enrich(new CacheKey("ip_dst_addr", 10L, broSc));
    Assert.assertEquals(actualMessage, new JSONObject());
}
Also used : JSONObject(org.json.simple.JSONObject) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) CacheKey(org.apache.metron.enrichment.bolt.CacheKey) Test(org.junit.Test)

Example 25 with SensorEnrichmentConfig

use of org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig in project metron by apache.

the class GenericEnrichmentBoltTest method test.

@Test
public void test() throws IOException {
    when(tuple.getSourceComponent()).thenReturn("unit test component");
    when(tuple.getSourceStreamId()).thenReturn("unit test stream");
    String key = "someKey";
    String enrichmentType = "enrichmentType";
    Enrichment<EnrichmentAdapter<CacheKey>> testEnrichment = new Enrichment<>();
    testEnrichment.setType(enrichmentType);
    testEnrichment.setAdapter(enrichmentAdapter);
    GenericEnrichmentBolt genericEnrichmentBolt = new GenericEnrichmentBolt("zookeeperUrl") {

        @Override
        protected void initializeStellar() {
        // do not initialize stellar here.
        }
    };
    genericEnrichmentBolt.setCuratorFramework(client);
    genericEnrichmentBolt.setZKCache(cache);
    genericEnrichmentBolt.getConfigurations().updateSensorEnrichmentConfig(sensorType, new FileInputStream(sampleSensorEnrichmentConfigPath));
    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());
    genericEnrichmentBolt.getConfigurations().updateGlobalConfig(globalConfig);
    try {
        genericEnrichmentBolt.prepare(new HashMap(), topologyContext, outputCollector);
        fail("Should fail if a maxCacheSize property is not set");
    } catch (IllegalStateException e) {
    }
    genericEnrichmentBolt.withMaxCacheSize(100);
    try {
        genericEnrichmentBolt.prepare(new HashMap(), topologyContext, outputCollector);
        fail("Should fail if a maxTimeRetain property is not set");
    } catch (IllegalStateException e) {
    }
    genericEnrichmentBolt.withMaxTimeRetain(10000);
    try {
        genericEnrichmentBolt.prepare(new HashMap(), topologyContext, outputCollector);
        fail("Should fail if an adapter is not set");
    } catch (IllegalStateException e) {
    }
    genericEnrichmentBolt.withEnrichment(testEnrichment);
    when(enrichmentAdapter.initializeAdapter(globalConfig)).thenReturn(true);
    genericEnrichmentBolt.prepare(new HashMap(), topologyContext, outputCollector);
    verify(enrichmentAdapter, times(1)).initializeAdapter(globalConfig);
    when(enrichmentAdapter.initializeAdapter(globalConfig)).thenReturn(false);
    UnitTestHelper.setLog4jLevel(GenericEnrichmentBolt.class, Level.FATAL);
    try {
        genericEnrichmentBolt.prepare(new HashMap(), topologyContext, outputCollector);
        fail("An exception should be thrown if enrichment adapter initialization fails");
    } catch (IllegalStateException e) {
    }
    UnitTestHelper.setLog4jLevel(GenericEnrichmentBolt.class, Level.ERROR);
    genericEnrichmentBolt.declareOutputFields(declarer);
    verify(declarer, times(1)).declareStream(eq(enrichmentType), argThat(new FieldsMatcher("key", "message", "subgroup")));
    verify(declarer, times(1)).declareStream(eq("error"), argThat(new FieldsMatcher("message")));
    when(tuple.getStringByField("key")).thenReturn(null);
    UnitTestHelper.setLog4jLevel(GenericEnrichmentBolt.class, Level.FATAL);
    genericEnrichmentBolt.execute(tuple);
    UnitTestHelper.setLog4jLevel(GenericEnrichmentBolt.class, Level.ERROR);
    MetronError error = new MetronError().withErrorType(Constants.ErrorType.ENRICHMENT_ERROR).withThrowable(new Exception("Could not parse binary stream to JSON"));
    verify(outputCollector, times(1)).emit(eq(Constants.ERROR_STREAM), argThat(new MetronErrorJSONMatcher(error.getJSONObject())));
    when(tuple.getStringByField("key")).thenReturn(key);
    when(tuple.getValueByField("message")).thenReturn(originalMessage);
    when(enrichmentAdapter.enrich(any())).thenReturn(new JSONObject());
    genericEnrichmentBolt.execute(tuple);
    verify(outputCollector, times(1)).emit(eq(enrichmentType), argThat(new EnrichedMessageMatcher(key, new JSONObject(ImmutableMap.of("source.type", "test")))));
    reset(enrichmentAdapter);
    SensorEnrichmentConfig sensorEnrichmentConfig = SensorEnrichmentConfig.fromBytes(ConfigurationsUtils.readSensorEnrichmentConfigsFromFile(TestConstants.SAMPLE_CONFIG_PATH).get(sensorType));
    sensorEnrichmentConfig.getConfiguration().put(GenericEnrichmentBolt.STELLAR_CONTEXT_CONF, genericEnrichmentBolt.getStellarContext());
    CacheKey cacheKey1 = new CacheKey("field1", "value1", sensorEnrichmentConfig);
    CacheKey cacheKey2 = new CacheKey("field2", "value2", sensorEnrichmentConfig);
    genericEnrichmentBolt.cache.invalidateAll();
    when(enrichmentAdapter.getOutputPrefix(cacheKey1)).thenReturn("field1");
    when(enrichmentAdapter.getOutputPrefix(cacheKey2)).thenReturn("field2");
    when(enrichmentAdapter.enrich(cacheKey1)).thenReturn(enrichedField1);
    when(enrichmentAdapter.enrich(cacheKey2)).thenReturn(enrichedField2);
    genericEnrichmentBolt.execute(tuple);
    verify(enrichmentAdapter, times(1)).logAccess(cacheKey1);
    verify(enrichmentAdapter, times(1)).logAccess(cacheKey2);
    verify(outputCollector, times(1)).emit(eq(enrichmentType), argThat(new EnrichedMessageMatcher(key, enrichedMessage)));
    reset(outputCollector);
    genericEnrichmentBolt.cache.invalidateAll();
    when(enrichmentAdapter.enrich(cacheKey1)).thenReturn(null);
    genericEnrichmentBolt.execute(tuple);
    error = new MetronError().withErrorType(Constants.ErrorType.ENRICHMENT_ERROR).withErrorFields(new HashSet<String>() {

        {
            add("field1");
        }
    }).addRawMessage(new JSONObject() {

        {
            put("field1", "value1");
            put("field2", "value2");
            put("source.type", "test");
        }
    }).withThrowable(new Exception("[Metron] Could not enrich string: value1"));
    verify(outputCollector, times(1)).emit(eq(Constants.ERROR_STREAM), argThat(new MetronErrorJSONMatcher(error.getJSONObject())));
}
Also used : Enrichment(org.apache.metron.enrichment.configuration.Enrichment) MetronErrorJSONMatcher(org.apache.metron.test.error.MetronErrorJSONMatcher) EnrichmentAdapter(org.apache.metron.enrichment.interfaces.EnrichmentAdapter) HashMap(java.util.HashMap) MetronError(org.apache.metron.common.error.MetronError) FileInputStream(java.io.FileInputStream) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) File(java.io.File) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) HashSet(java.util.HashSet) BaseEnrichmentBoltTest(org.apache.metron.test.bolt.BaseEnrichmentBoltTest) Test(org.junit.Test)

Aggregations

SensorEnrichmentConfig (org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig)30 Test (org.junit.Test)22 JSONObject (org.json.simple.JSONObject)15 HashMap (java.util.HashMap)11 CacheKey (org.apache.metron.enrichment.bolt.CacheKey)6 File (java.io.File)4 MetronError (org.apache.metron.common.error.MetronError)3 FileInputStream (java.io.FileInputStream)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 SetDataBuilder (org.apache.curator.framework.api.SetDataBuilder)2 EnrichmentConfigurations (org.apache.metron.common.configuration.EnrichmentConfigurations)2 SensorEnrichmentUpdateConfig (org.apache.metron.common.configuration.enrichment.SensorEnrichmentUpdateConfig)2 ThreatTriageProcessor (org.apache.metron.threatintel.triage.ThreatTriageProcessor)2 Values (org.apache.storm.tuple.Values)2 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 BufferedReader (java.io.BufferedReader)1 FileReader (java.io.FileReader)1 IOException (java.io.IOException)1 EnrichmentConfig (org.apache.metron.common.configuration.enrichment.EnrichmentConfig)1