Search in sources :

Example 1 with Source

use of com.nextdoor.bender.config.Source 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 Source

use of com.nextdoor.bender.config.Source in project bender by Nextdoor.

the class BaseHandler method init.

/**
 * Loads @{link com.nextdoor.bender.config.Configuration} from a resource file and initializes
 * classes.
 *
 * @param ctx function context as specified when function is invoked by lambda.
 * @throws HandlerException error while loading the @{link
 *         com.nextdoor.bender.config.Configuration}.
 */
public void init(Context ctx) throws HandlerException {
    /*
     * Function alias is the last part of the Function ARN
     */
    String alias = null;
    String[] tokens = ctx.getInvokedFunctionArn().split(":");
    if (tokens.length == 7) {
        alias = "$LATEST";
    } else if (tokens.length == 8) {
        alias = tokens[7];
    }
    BenderLayout.ALIAS = alias;
    BenderLayout.VERSION = ctx.getFunctionVersion();
    /*
     * Create a new monitor and then get a static copy of it
     */
    monitor = Monitor.getInstance();
    monitor.addTag("functionName", ctx.getFunctionName());
    monitor.addTag("functionVersion", alias);
    String configFile;
    /*
     * TODO: Replace this to always use env vars. Code was written prior to
     * lambda env vars existing.
     */
    if (System.getenv("BENDER_CONFIG") != null) {
        configFile = System.getenv("BENDER_CONFIG");
    } else if (CONFIG_FILE == null) {
        configFile = "/config/" + alias;
    } else {
        configFile = CONFIG_FILE;
    }
    logger.info(String.format("Bender Initializing (config: %s)", configFile));
    try {
        if (configFile.startsWith("s3://")) {
            config = BenderConfig.load(s3ClientFactory, new AmazonS3URI(configFile));
        } else {
            config = BenderConfig.load(configFile);
        }
    } catch (ConfigurationException e) {
        throw new HandlerException("Error loading configuration: " + e.getMessage(), e);
    }
    HandlerResources handlerResources;
    try {
        handlerResources = new HandlerResources(config);
    } catch (ClassNotFoundException e) {
        throw new HandlerException("Unable to load resource: " + e.getMessage(), e);
    }
    /*
     * Register reporters
     */
    monitor.addReporters(handlerResources.getReporters());
    /*
     * Init other things
     */
    wrapper = handlerResources.getWrapperFactory().newInstance();
    ser = handlerResources.getSerializerProcessor();
    setIpcService(new IpcSenderService(handlerResources.getTransportFactory()));
    sources = new ArrayList<Source>(handlerResources.getSources().values());
    initialized = true;
}
Also used : IpcSenderService(com.nextdoor.bender.ipc.IpcSenderService) ConfigurationException(com.nextdoor.bender.config.ConfigurationException) AmazonS3URI(com.amazonaws.services.s3.AmazonS3URI) Source(com.nextdoor.bender.config.Source) HandlerResources(com.nextdoor.bender.config.HandlerResources)

Aggregations

AmazonS3URI (com.amazonaws.services.s3.AmazonS3URI)2 ConfigurationException (com.nextdoor.bender.config.ConfigurationException)2 HandlerResources (com.nextdoor.bender.config.HandlerResources)2 Source (com.nextdoor.bender.config.Source)2 IpcSenderService (com.nextdoor.bender.ipc.IpcSenderService)2 Context (com.amazonaws.services.lambda.runtime.Context)1 InternalEvent (com.nextdoor.bender.InternalEvent)1 AmazonS3ClientFactory (com.nextdoor.bender.aws.AmazonS3ClientFactory)1 BenderConfig (com.nextdoor.bender.config.BenderConfig)1 DeserializedEvent (com.nextdoor.bender.deserializer.DeserializedEvent)1 DeserializerProcessor (com.nextdoor.bender.deserializer.DeserializerProcessor)1 TransportException (com.nextdoor.bender.ipc.TransportException)1 BenderLayout (com.nextdoor.bender.logging.BenderLayout)1 Monitor (com.nextdoor.bender.monitoring.Monitor)1 Stat (com.nextdoor.bender.monitoring.Stat)1 OperationProcessor (com.nextdoor.bender.operation.OperationProcessor)1 SerializationException (com.nextdoor.bender.serializer.SerializationException)1 SerializerProcessor (com.nextdoor.bender.serializer.SerializerProcessor)1 Wrapper (com.nextdoor.bender.wrapper.Wrapper)1 IOException (java.io.IOException)1