Search in sources :

Example 1 with InternalEvent

use of com.nextdoor.bender.InternalEvent in project bender by Nextdoor.

the class BaseHandler method processInternal.

/**
 * Method called by Handler implementations to process records.
 *
 * @param context Lambda invocation context.
 * @throws HandlerException
 */
private void processInternal(Context context) throws HandlerException {
    Stat runtime = new Stat("runtime.ns");
    runtime.start();
    Source source = this.getSource();
    DeserializerProcessor deser = source.getDeserProcessor();
    List<OperationProcessor> operations = source.getOperationProcessors();
    List<String> containsStrings = source.getContainsStrings();
    List<Pattern> regexPatterns = source.getRegexPatterns();
    this.getIpcService().setContext(context);
    Iterator<InternalEvent> events = this.getInternalEventIterator();
    /*
     * For logging purposes log when the function started running
     */
    this.monitor.invokeTimeNow();
    AtomicLong eventCount = new AtomicLong(0);
    AtomicLong oldestArrivalTime = new AtomicLong(System.currentTimeMillis());
    AtomicLong oldestOccurrenceTime = new AtomicLong(System.currentTimeMillis());
    /*
     * Process each record
     */
    int characteristics = Spliterator.IMMUTABLE;
    Spliterator<InternalEvent> spliterator = Spliterators.spliteratorUnknownSize(events, characteristics);
    Stream<InternalEvent> input = StreamSupport.stream(spliterator, false);
    /*
     * Filter out raw events
     */
    Stream<InternalEvent> filtered = input.filter(/*
         * Perform regex filter
         */
    ievent -> {
        eventCount.incrementAndGet();
        String eventStr = ievent.getEventString();
        /*
           * Apply String contains filters before deserialization
           */
        for (String containsString : containsStrings) {
            if (eventStr.contains(containsString)) {
                return false;
            }
        }
        /*
           * Apply regex patterns before deserialization
           */
        for (Pattern regexPattern : regexPatterns) {
            Matcher m = regexPattern.matcher(eventStr);
            if (m.find()) {
                return false;
            }
        }
        return true;
    });
    /*
     * Deserialize
     */
    Stream<InternalEvent> deserialized = filtered.map(ievent -> {
        DeserializedEvent data = deser.deserialize(ievent.getEventString());
        if (data == null || data.getPayload() == null) {
            logger.warn("Failed to deserialize: " + ievent.getEventString());
            return null;
        }
        ievent.setEventObj(data);
        return ievent;
    }).filter(Objects::nonNull);
    /*
     * Perform Operations
     */
    Stream<InternalEvent> operated = deserialized;
    for (OperationProcessor operation : operations) {
        operated = operation.perform(operated);
    }
    /*
     * Serialize
     */
    Stream<InternalEvent> serialized = operated.map(ievent -> {
        try {
            String raw = null;
            raw = this.ser.serialize(this.wrapper.getWrapped(ievent));
            ievent.setSerialized(raw);
            return ievent;
        } catch (SerializationException e) {
            return null;
        }
    }).filter(Objects::nonNull);
    /*
     * Transport
     */
    serialized.forEach(ievent -> {
        /*
       * Update times
       */
        updateOldest(oldestArrivalTime, ievent.getArrivalTime());
        updateOldest(oldestOccurrenceTime, ievent.getEventTime());
        try {
            this.getIpcService().add(ievent);
        } catch (TransportException e) {
            logger.warn("error adding event", e);
        }
    });
    /*
     * Wait for transporters to finish
     */
    try {
        this.getIpcService().shutdown();
    } catch (TransportException e) {
        throw new HandlerException("encounted TransportException while shutting down ipcService", e);
    } catch (InterruptedException e) {
        throw new HandlerException("thread was interruptedwhile shutting down ipcService", e);
    } finally {
        String evtSource = this.getSourceName();
        runtime.stop();
        if (!this.skipWriteStats) {
            writeStats(eventCount.get(), oldestArrivalTime.get(), oldestOccurrenceTime.get(), evtSource, runtime);
        }
        if (logger.isTraceEnabled()) {
            getGCStats();
        }
    }
}
Also used : Monitor(com.nextdoor.bender.monitoring.Monitor) Spliterators(java.util.Spliterators) Wrapper(com.nextdoor.bender.wrapper.Wrapper) Context(com.amazonaws.services.lambda.runtime.Context) Stat(com.nextdoor.bender.monitoring.Stat) InternalEvent(com.nextdoor.bender.InternalEvent) OperationProcessor(com.nextdoor.bender.operation.OperationProcessor) ArrayList(java.util.ArrayList) IpcSenderService(com.nextdoor.bender.ipc.IpcSenderService) Logger(org.apache.log4j.Logger) Matcher(java.util.regex.Matcher) GarbageCollectorMXBean(java.lang.management.GarbageCollectorMXBean) AmazonS3ClientFactory(com.nextdoor.bender.aws.AmazonS3ClientFactory) TransportException(com.nextdoor.bender.ipc.TransportException) BenderConfig(com.nextdoor.bender.config.BenderConfig) StreamSupport(java.util.stream.StreamSupport) ManagementFactory(java.lang.management.ManagementFactory) DeserializedEvent(com.nextdoor.bender.deserializer.DeserializedEvent) Iterator(java.util.Iterator) IOException(java.io.IOException) SerializerProcessor(com.nextdoor.bender.serializer.SerializerProcessor) ConfigurationException(com.nextdoor.bender.config.ConfigurationException) Objects(java.util.Objects) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Stream(java.util.stream.Stream) SerializationException(com.nextdoor.bender.serializer.SerializationException) BenderLayout(com.nextdoor.bender.logging.BenderLayout) Pattern(java.util.regex.Pattern) Source(com.nextdoor.bender.config.Source) Spliterator(java.util.Spliterator) DeserializerProcessor(com.nextdoor.bender.deserializer.DeserializerProcessor) AmazonS3URI(com.amazonaws.services.s3.AmazonS3URI) HandlerResources(com.nextdoor.bender.config.HandlerResources) Pattern(java.util.regex.Pattern) DeserializedEvent(com.nextdoor.bender.deserializer.DeserializedEvent) SerializationException(com.nextdoor.bender.serializer.SerializationException) Matcher(java.util.regex.Matcher) OperationProcessor(com.nextdoor.bender.operation.OperationProcessor) TransportException(com.nextdoor.bender.ipc.TransportException) Source(com.nextdoor.bender.config.Source) InternalEvent(com.nextdoor.bender.InternalEvent) AtomicLong(java.util.concurrent.atomic.AtomicLong) Stat(com.nextdoor.bender.monitoring.Stat) Objects(java.util.Objects) DeserializerProcessor(com.nextdoor.bender.deserializer.DeserializerProcessor)

Example 2 with InternalEvent

use of com.nextdoor.bender.InternalEvent in project bender by Nextdoor.

the class GenericTransportBufferTest method testAddBufferFull.

@Test(expected = IllegalStateException.class)
public void testAddBufferFull() throws IOException {
    GenericTransportSerializer serializer = mock(GenericTransportSerializer.class);
    doReturn("foo".getBytes()).when(serializer).serialize(any(InternalEvent.class));
    GenericTransportBuffer buffer = new GenericTransportBuffer(1, false, serializer);
    InternalEvent mockEvent = mock(InternalEvent.class);
    buffer.add(mockEvent);
    buffer.add(mockEvent);
}
Also used : GenericTransportSerializer(com.nextdoor.bender.ipc.generic.GenericTransportSerializer) GenericTransportBuffer(com.nextdoor.bender.ipc.generic.GenericTransportBuffer) InternalEvent(com.nextdoor.bender.InternalEvent) Test(org.junit.Test)

Example 3 with InternalEvent

use of com.nextdoor.bender.InternalEvent in project bender by Nextdoor.

the class GenericTransportBufferTest method testClear.

@Test
public void testClear() throws IOException {
    GenericTransportSerializer serializer = mock(GenericTransportSerializer.class);
    doReturn("foo".getBytes()).when(serializer).serialize(any(InternalEvent.class));
    GenericTransportBuffer buffer = new GenericTransportBuffer(1, false, serializer);
    InternalEvent mockEvent = mock(InternalEvent.class);
    buffer.add(mockEvent);
    buffer.close();
    String actual = new String(buffer.getInternalBuffer().toByteArray());
    assertEquals("foo", actual);
    buffer.clear();
    assertEquals(true, buffer.isEmpty());
}
Also used : GenericTransportSerializer(com.nextdoor.bender.ipc.generic.GenericTransportSerializer) GenericTransportBuffer(com.nextdoor.bender.ipc.generic.GenericTransportBuffer) InternalEvent(com.nextdoor.bender.InternalEvent) Test(org.junit.Test)

Example 4 with InternalEvent

use of com.nextdoor.bender.InternalEvent in project bender by Nextdoor.

the class DatadogTransportSerializerTest method shouldSerialize.

@Test
public void shouldSerialize() {
    StringValueConfig apiKey = new StringValueConfig("foo");
    DatadogTransportSerializer serializer = new DatadogTransportSerializer(apiKey);
    InternalEvent record = new InternalEvent("", null, 0);
    record.setEventTime(1521645289128L);
    record.setSerialized("bar");
    String actual = new String(serializer.serialize(record), StandardCharsets.UTF_8);
    assertEquals("foo bar\n", actual);
}
Also used : StringValueConfig(com.nextdoor.bender.config.value.StringValueConfig) InternalEvent(com.nextdoor.bender.InternalEvent) Test(org.junit.Test)

Example 5 with InternalEvent

use of com.nextdoor.bender.InternalEvent in project bender by Nextdoor.

the class ElasticSearchTansportSerializerTest method testPartitionRouting.

@Test
public void testPartitionRouting() throws UnsupportedEncodingException, IOException {
    ElasticSearchTransportSerializer serializer = new ElasticSearchTransportSerializer(true, "event", "log", true);
    InternalEvent record = new DummyEvent("foo", 0);
    record.setSerialized("foo");
    record.getPartitions().put("test_key", "test_value");
    String actual = new String(serializer.serialize(record));
    String expected = TestUtils.getResourceString(this.getClass(), "routing_output.txt");
    /*
     * Verify build output does contain hash
     */
    assertEquals(expected, actual);
}
Also used : InternalEvent(com.nextdoor.bender.InternalEvent) Test(org.junit.Test)

Aggregations

InternalEvent (com.nextdoor.bender.InternalEvent)68 Test (org.junit.Test)67 LinkedHashMap (java.util.LinkedHashMap)17 HashMap (java.util.HashMap)13 ArrayList (java.util.ArrayList)12 TestContext (com.nextdoor.bender.aws.TestContext)10 AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)9 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)9 DummyDeserializedEvent (com.nextdoor.bender.testutils.DummyDeserializerHelper.DummyDeserializedEvent)9 JsonElement (com.google.gson.JsonElement)7 JsonParser (com.google.gson.JsonParser)7 OperationTest (com.nextdoor.bender.operations.json.OperationTest)7 DummyOperationFactory (com.nextdoor.bender.testutils.DummyOperationHelper.DummyOperationFactory)6 GenericTransportBuffer (com.nextdoor.bender.ipc.generic.GenericTransportBuffer)5 GenericTransportSerializer (com.nextdoor.bender.ipc.generic.GenericTransportSerializer)5 DummyOperation (com.nextdoor.bender.testutils.DummyOperationHelper.DummyOperation)4 UploadPartResult (com.amazonaws.services.s3.model.UploadPartResult)3 Stat (com.nextdoor.bender.monitoring.Stat)3 KeyNameOperation (com.nextdoor.bender.operation.json.key.KeyNameOperation)3 ByteArrayOutputStream (org.apache.commons.io.output.ByteArrayOutputStream)3