Search in sources :

Example 6 with MetronError

use of org.apache.metron.common.error.MetronError 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 7 with MetronError

use of org.apache.metron.common.error.MetronError in project metron by apache.

the class WriterBolt method execute.

@Override
public void execute(Tuple tuple) {
    JSONObject message = null;
    try {
        message = (JSONObject) messageGetStrategy.get(tuple);
        handler.write(sensorType, tuple, message, configuration, messageGetStrategy);
        if (!handler.handleAck()) {
            collector.ack(tuple);
        }
    } catch (Throwable e) {
        MetronError error = new MetronError().withErrorType(errorType).withThrowable(e).withSensorType(sensorType).addRawMessage(message);
        ErrorUtils.handleError(collector, error);
        collector.ack(tuple);
    }
}
Also used : JSONObject(org.json.simple.JSONObject) MetronError(org.apache.metron.common.error.MetronError)

Example 8 with MetronError

use of org.apache.metron.common.error.MetronError in project metron by apache.

the class ParserBoltTest method testInvalid.

@Test
public void testInvalid() throws Exception {
    String sensorType = "yaf";
    ParserBolt parserBolt = new ParserBolt("zookeeperUrl", sensorType, parser, new WriterHandler(writer)) {

        @Override
        protected ConfigurationsUpdater<ParserConfigurations> createUpdater() {
            return ParserBoltTest.createUpdater();
        }
    };
    buildGlobalConfig(parserBolt);
    parserBolt.setCuratorFramework(client);
    parserBolt.setZKCache(cache);
    parserBolt.prepare(new HashMap(), topologyContext, outputCollector);
    byte[] sampleBinary = "some binary message".getBytes();
    when(tuple.getBinary(0)).thenReturn(sampleBinary);
    JSONObject parsedMessage = new JSONObject();
    parsedMessage.put("field", "invalidValue");
    parsedMessage.put("guid", "this-is-unique-identifier-for-tuple");
    List<JSONObject> messageList = new ArrayList<>();
    messageList.add(parsedMessage);
    when(parser.parseOptional(sampleBinary)).thenReturn(Optional.of(messageList));
    when(parser.validate(parsedMessage)).thenReturn(true);
    parserBolt.execute(tuple);
    MetronError error = new MetronError().withErrorType(Constants.ErrorType.PARSER_INVALID).withSensorType(sensorType).withErrorFields(new HashSet<String>() {

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

        {
            put("field", "invalidValue");
            put("source.type", "yaf");
            put("guid", "this-is-unique-identifier-for-tuple");
        }
    });
    verify(outputCollector, times(1)).emit(eq(Constants.ERROR_STREAM), argThat(new MetronErrorJSONMatcher(error.getJSONObject())));
}
Also used : MetronErrorJSONMatcher(org.apache.metron.test.error.MetronErrorJSONMatcher) JSONObject(org.json.simple.JSONObject) MetronError(org.apache.metron.common.error.MetronError) ParserConfigurations(org.apache.metron.common.configuration.ParserConfigurations) BaseBoltTest(org.apache.metron.test.bolt.BaseBoltTest) Test(org.junit.Test)

Example 9 with MetronError

use of org.apache.metron.common.error.MetronError in project metron by apache.

the class WriterBoltTest method testNonBatchErrorPathErrorInWrite.

@Test
public void testNonBatchErrorPathErrorInWrite() throws Exception {
    ParserConfigurations configurations = getConfigurations(1);
    String sensorType = "test";
    Tuple t = mock(Tuple.class);
    when(t.toString()).thenReturn("tuple");
    when(t.getValueByField(eq("message"))).thenReturn(new JSONObject());
    WriterBolt bolt = new WriterBolt(new WriterHandler(writer), configurations, sensorType);
    bolt.prepare(new HashMap(), topologyContext, outputCollector);
    doThrow(new Exception("write error")).when(writer).write(any(), any(), any(), any());
    verify(writer, times(1)).init();
    bolt.execute(t);
    verify(outputCollector, times(1)).ack(t);
    verify(writer, times(1)).write(eq(sensorType), any(), any(), any());
    verify(outputCollector, times(1)).reportError(any());
    verify(outputCollector, times(0)).fail(any());
    MetronError error = new MetronError().withErrorType(Constants.ErrorType.DEFAULT_ERROR).withThrowable(new IllegalStateException("Unhandled bulk errors in response: {java.lang.Exception: write error=[tuple]}")).withSensorType(sensorType).addRawMessage(new JSONObject());
    verify(outputCollector, times(1)).emit(eq(Constants.ERROR_STREAM), argThat(new MetronErrorJSONMatcher(error.getJSONObject())));
}
Also used : MetronErrorJSONMatcher(org.apache.metron.test.error.MetronErrorJSONMatcher) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) MetronError(org.apache.metron.common.error.MetronError) ParserConfigurations(org.apache.metron.common.configuration.ParserConfigurations) Tuple(org.apache.storm.tuple.Tuple) BaseBoltTest(org.apache.metron.test.bolt.BaseBoltTest) Test(org.junit.Test)

Example 10 with MetronError

use of org.apache.metron.common.error.MetronError in project metron by apache.

the class BulkWriterComponentTest method writeShouldProperlyHandleWriterException.

@Test
public void writeShouldProperlyHandleWriterException() throws Exception {
    Throwable e = new Exception("test exception");
    MetronError error = new MetronError().withSensorType(sensorType).withErrorType(Constants.ErrorType.INDEXING_ERROR).withThrowable(e).withRawMessages(Arrays.asList(message1, message2));
    BulkWriterResponse response = new BulkWriterResponse();
    response.addAllErrors(e, tupleList);
    when(bulkMessageWriter.write(sensorType, configurations, Arrays.asList(tuple1, tuple2), Arrays.asList(message1, message2))).thenThrow(e);
    BulkWriterComponent<JSONObject> bulkWriterComponent = new BulkWriterComponent<>(collector);
    bulkWriterComponent.write(sensorType, tuple1, message1, bulkMessageWriter, configurations, messageGetStrategy);
    bulkWriterComponent.write(sensorType, tuple2, message2, bulkMessageWriter, configurations, messageGetStrategy);
    verifyStatic(times(1));
    ErrorUtils.handleError(collector, error);
}
Also used : JSONObject(org.json.simple.JSONObject) MetronError(org.apache.metron.common.error.MetronError) ExpectedException(org.junit.rules.ExpectedException) BulkWriterResponse(org.apache.metron.common.writer.BulkWriterResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

MetronError (org.apache.metron.common.error.MetronError)17 JSONObject (org.json.simple.JSONObject)11 Test (org.junit.Test)9 MetronErrorJSONMatcher (org.apache.metron.test.error.MetronErrorJSONMatcher)6 HashMap (java.util.HashMap)5 Values (org.apache.storm.tuple.Values)4 ExpectedException (org.junit.rules.ExpectedException)4 IOException (java.io.IOException)3 ParserConfigurations (org.apache.metron.common.configuration.ParserConfigurations)3 SensorEnrichmentConfig (org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig)3 BaseBoltTest (org.apache.metron.test.bolt.BaseBoltTest)3 Tuple (org.apache.storm.tuple.Tuple)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 BulkWriterResponse (org.apache.metron.common.writer.BulkWriterResponse)2 BaseEnrichmentBoltTest (org.apache.metron.test.bolt.BaseEnrichmentBoltTest)2 OutputCollector (org.apache.storm.task.OutputCollector)2 ParseException (org.json.simple.parser.ParseException)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 LoadingCache (com.github.benmanes.caffeine.cache.LoadingCache)1