Search in sources :

Example 1 with TransportException

use of com.nextdoor.bender.ipc.TransportException 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 TransportException

use of com.nextdoor.bender.ipc.TransportException in project bender by Nextdoor.

the class HandlerTest method testExceptionHandling.

@Test(expected = TransportException.class)
public void testExceptionHandling() throws Throwable {
    TestContext ctx = new TestContext();
    ctx.setFunctionName("unittest");
    ctx.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test-function:staging");
    /*
     * Invoke handler
     */
    BaseHandler<T> fhandler = (BaseHandler<T>) getHandler();
    fhandler.init(ctx);
    IpcSenderService ipcSpy = spy(fhandler.getIpcService());
    doThrow(new TransportException("expected")).when(ipcSpy).shutdown();
    fhandler.setIpcService(ipcSpy);
    T event = getTestEvent();
    try {
        fhandler.handler(event, ctx);
    } catch (Exception e) {
        throw e.getCause().getCause();
    }
}
Also used : IpcSenderService(com.nextdoor.bender.ipc.IpcSenderService) TestContext(com.nextdoor.bender.aws.TestContext) TransportException(com.nextdoor.bender.ipc.TransportException) TransportException(com.nextdoor.bender.ipc.TransportException) Test(org.junit.Test)

Example 3 with TransportException

use of com.nextdoor.bender.ipc.TransportException in project bender by Nextdoor.

the class S3Transport method compress.

protected ByteArrayOutputStream compress(ByteArrayOutputStream raw) throws TransportException {
    ByteArrayOutputStream compressed = new ByteArrayOutputStream();
    BZip2CompressorOutputStream bcos = null;
    try {
        bcos = new BZip2CompressorOutputStream(compressed);
    } catch (IOException e) {
        throw new TransportException("unable to open compressed stream", e);
    }
    try {
        raw.writeTo(bcos);
        bcos.flush();
    } catch (IOException e) {
        throw new TransportException("unable to compress data", e);
    } finally {
        try {
            bcos.close();
        } catch (IOException e) {
        }
    }
    return compressed;
}
Also used : BZip2CompressorOutputStream(org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) IOException(java.io.IOException) TransportException(com.nextdoor.bender.ipc.TransportException)

Example 4 with TransportException

use of com.nextdoor.bender.ipc.TransportException in project bender by Nextdoor.

the class BaseHandlerTest method testGeneralTransportExceptionOnShutdown.

@Test(expected = TransportException.class)
public void testGeneralTransportExceptionOnShutdown() throws Throwable {
    BaseHandler.CONFIG_FILE = "/config/handler_config.json";
    List<DummyEvent> events = new ArrayList<DummyEvent>(1);
    events.add(new DummyEvent("foo", 0));
    TestContext context = new TestContext();
    context.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test:tag");
    handler.init(context);
    IpcSenderService spy = spy(handler.getIpcService());
    handler.setIpcService(spy);
    doThrow(new TransportException("expected")).when(spy).shutdown();
    try {
        handler.handler(events, context);
    } catch (Exception e) {
        throw e.getCause().getCause();
    }
}
Also used : IpcSenderService(com.nextdoor.bender.ipc.IpcSenderService) TestContext(com.nextdoor.bender.aws.TestContext) ArrayList(java.util.ArrayList) TransportException(com.nextdoor.bender.ipc.TransportException) TransportException(com.nextdoor.bender.ipc.TransportException) IOException(java.io.IOException) DeserializationException(com.nextdoor.bender.deserializer.DeserializationException) SerializationException(com.nextdoor.bender.serializer.SerializationException) OperationException(com.nextdoor.bender.operation.OperationException) Test(org.junit.Test)

Example 5 with TransportException

use of com.nextdoor.bender.ipc.TransportException in project bender by Nextdoor.

the class HttpTransportTest method testGzipErrorsResponse.

@Test(expected = TransportException.class)
public void testGzipErrorsResponse() throws TransportException, IOException {
    byte[] respPayload = "gzip resp".getBytes(StandardCharsets.UTF_8);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream os = new GZIPOutputStream(baos);
    os.write(respPayload);
    os.close();
    byte[] compressedResponse = baos.toByteArray();
    HttpClient client = getMockClientWithResponse(compressedResponse, ContentType.DEFAULT_BINARY, HttpStatus.SC_INTERNAL_SERVER_ERROR, true);
    HttpTransport transport = new HttpTransport(client, "", true, 1, 1);
    try {
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("http transport call failed because \"expected failure\" payload response \"gzip resp\"", e.getCause().getMessage());
        throw e;
    }
}
Also used : GZIPOutputStream(java.util.zip.GZIPOutputStream) HttpClient(org.apache.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TransportException(com.nextdoor.bender.ipc.TransportException) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

TransportException (com.nextdoor.bender.ipc.TransportException)20 IOException (java.io.IOException)16 Test (org.junit.Test)10 TestContext (com.nextdoor.bender.aws.TestContext)5 IpcSenderService (com.nextdoor.bender.ipc.IpcSenderService)5 AmazonClientException (com.amazonaws.AmazonClientException)3 InitiateMultipartUploadRequest (com.amazonaws.services.s3.model.InitiateMultipartUploadRequest)3 InitiateMultipartUploadResult (com.amazonaws.services.s3.model.InitiateMultipartUploadResult)3 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)3 UploadPartResult (com.amazonaws.services.s3.model.UploadPartResult)3 RetriesExhaustedException (com.evanlennick.retry4j.exception.RetriesExhaustedException)3 JsonSyntaxException (com.google.gson.JsonSyntaxException)3 SerializationException (com.nextdoor.bender.serializer.SerializationException)3 ArrayList (java.util.ArrayList)3 HttpClient (org.apache.http.client.HttpClient)3 Context (com.amazonaws.services.lambda.runtime.Context)2 AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)2 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)2 CallExecutor (com.evanlennick.retry4j.CallExecutor)2 UnexpectedException (com.evanlennick.retry4j.exception.UnexpectedException)2