Search in sources :

Example 1 with SiddhiAppRuntimeBuilder

use of org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder in project siddhi by wso2.

the class AggregationParser method parse.

public static AggregationRuntime parse(AggregationDefinition aggregationDefinition, SiddhiAppContext siddhiAppContext, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap, SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder) {
    if (aggregationDefinition == null) {
        throw new SiddhiAppCreationException("AggregationDefinition instance is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'");
    }
    if (aggregationDefinition.getTimePeriod() == null) {
        throw new SiddhiAppCreationException("AggregationDefinition '" + aggregationDefinition.getId() + "'s timePeriod is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (aggregationDefinition.getSelector() == null) {
        throw new SiddhiAppCreationException("AggregationDefinition '" + aggregationDefinition.getId() + "'s selection is not defined. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (streamDefinitionMap.get(aggregationDefinition.getBasicSingleInputStream().getStreamId()) == null) {
        throw new SiddhiAppCreationException("Stream " + aggregationDefinition.getBasicSingleInputStream().getStreamId() + " has not been defined");
    }
    try {
        List<VariableExpressionExecutor> incomingVariableExpressionExecutors = new ArrayList<>();
        String aggregatorName = aggregationDefinition.getId();
        StreamRuntime streamRuntime = InputStreamParser.parse(aggregationDefinition.getBasicSingleInputStream(), siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, incomingVariableExpressionExecutors, null, false, aggregatorName);
        // Get original meta for later use.
        MetaStreamEvent incomingMetaStreamEvent = (MetaStreamEvent) streamRuntime.getMetaComplexEvent();
        // Create new meta stream event.
        // This must hold the timestamp, group by attributes (if given) and the incremental attributes, in
        // onAfterWindowData array
        // Example format: AGG_TIMESTAMP, groupByAttribute1, groupByAttribute2, AGG_incAttribute1, AGG_incAttribute2
        // AGG_incAttribute1, AGG_incAttribute2 would have the same attribute names as in
        // finalListOfIncrementalAttributes
        // To enter data as onAfterWindowData
        incomingMetaStreamEvent.initializeAfterWindowData();
        List<ExpressionExecutor> incomingExpressionExecutors = new ArrayList<>();
        List<IncrementalAttributeAggregator> incrementalAttributeAggregators = new ArrayList<>();
        List<Variable> groupByVariableList = aggregationDefinition.getSelector().getGroupByList();
        boolean isProcessingOnExternalTime = aggregationDefinition.getAggregateAttribute() != null;
        // Expressions to get
        List<Expression> outputExpressions = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        // Expression executors to get
        List<ExpressionExecutor> outputExpressionExecutors = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        populateIncomingAggregatorsAndExecutors(aggregationDefinition, siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, groupByVariableList, outputExpressions);
        int baseAggregatorBeginIndex = incomingMetaStreamEvent.getOutputData().size();
        List<Expression> finalBaseAggregators = getFinalBaseAggregators(siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators);
        StreamDefinition incomingOutputStreamDefinition = StreamDefinition.id("");
        incomingOutputStreamDefinition.setQueryContextStartIndex(aggregationDefinition.getQueryContextStartIndex());
        incomingOutputStreamDefinition.setQueryContextEndIndex(aggregationDefinition.getQueryContextEndIndex());
        MetaStreamEvent processedMetaStreamEvent = new MetaStreamEvent();
        for (Attribute attribute : incomingMetaStreamEvent.getOutputData()) {
            incomingOutputStreamDefinition.attribute(attribute.getName(), attribute.getType());
            processedMetaStreamEvent.addOutputData(attribute);
        }
        incomingMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.addInputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        // Executors of processing meta
        List<VariableExpressionExecutor> processVariableExpressionExecutors = new ArrayList<>();
        boolean groupBy = aggregationDefinition.getSelector().getGroupByList().size() != 0;
        List<ExpressionExecutor> processExpressionExecutors = constructProcessExpressionExecutors(siddhiAppContext, tableMap, aggregatorName, baseAggregatorBeginIndex, finalBaseAggregators, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, groupBy);
        outputExpressionExecutors.addAll(outputExpressions.stream().map(expression -> ExpressionParser.parseExpression(expression, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, siddhiAppContext, groupBy, 0, aggregatorName)).collect(Collectors.toList()));
        // Create group by key generator
        GroupByKeyGenerator groupByKeyGenerator = null;
        if (groupBy) {
            groupByKeyGenerator = new GroupByKeyGenerator(groupByVariableList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiAppContext, aggregatorName);
        }
        // Create new scheduler
        EntryValveExecutor entryValveExecutor = new EntryValveExecutor(siddhiAppContext);
        LockWrapper lockWrapper = new LockWrapper(aggregatorName);
        lockWrapper.setLock(new ReentrantLock());
        Scheduler scheduler = SchedulerParser.parse(siddhiAppContext.getScheduledExecutorService(), entryValveExecutor, siddhiAppContext);
        scheduler.init(lockWrapper, aggregatorName);
        scheduler.setStreamEventPool(new StreamEventPool(processedMetaStreamEvent, 10));
        QueryParserHelper.reduceMetaComplexEvent(incomingMetaStreamEvent);
        QueryParserHelper.reduceMetaComplexEvent(processedMetaStreamEvent);
        QueryParserHelper.updateVariablePosition(incomingMetaStreamEvent, incomingVariableExpressionExecutors);
        QueryParserHelper.updateVariablePosition(processedMetaStreamEvent, processVariableExpressionExecutors);
        List<TimePeriod.Duration> incrementalDurations = getSortedPeriods(aggregationDefinition.getTimePeriod());
        Map<TimePeriod.Duration, Table> aggregationTables = initDefaultTables(aggregatorName, incrementalDurations, processedMetaStreamEvent.getOutputStreamDefinition(), siddhiAppRuntimeBuilder, aggregationDefinition.getAnnotations(), groupByVariableList);
        int bufferSize = 0;
        Element element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_BUFFER_SIZE, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            try {
                bufferSize = Integer.parseInt(element.getValue());
            } catch (NumberFormatException e) {
                throw new SiddhiAppCreationException(e.getMessage() + ": BufferSize must be an integer");
            }
        }
        if (bufferSize > 0) {
            TimePeriod.Duration rootDuration = incrementalDurations.get(0);
            if (rootDuration == TimePeriod.Duration.MONTHS || rootDuration == TimePeriod.Duration.YEARS) {
                throw new SiddhiAppCreationException("A buffer size greater than 0 can be provided, only when the " + "first duration value is seconds, minutes, hours or days");
            }
            if (!isProcessingOnExternalTime) {
                throw new SiddhiAppCreationException("Buffer size cannot be specified when events are aggregated " + "based on event arrival time.");
            // Buffer size is used to process out of order events. However, events would never be out of
            // order if they are processed based on event arrival time.
            }
        } else if (bufferSize < 0) {
            throw new SiddhiAppCreationException("Expected a positive integer as the buffer size, but found " + bufferSize + " as the provided value");
        }
        boolean ignoreEventsOlderThanBuffer = false;
        element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_IGNORE_EVENTS_OLDER_THAN_BUFFER, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            if (element.getValue().equalsIgnoreCase("true")) {
                ignoreEventsOlderThanBuffer = true;
            } else if (!element.getValue().equalsIgnoreCase("false")) {
                throw new SiddhiAppCreationException("IgnoreEventsOlderThanBuffer value must " + "be true or false");
            }
        }
        Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap = buildIncrementalExecutors(isProcessingOnExternalTime, processedMetaStreamEvent, processExpressionExecutors, groupByKeyGenerator, bufferSize, ignoreEventsOlderThanBuffer, incrementalDurations, aggregationTables, siddhiAppContext, aggregatorName);
        // Recreate in-memory data from tables
        RecreateInMemoryData recreateInMemoryData = new RecreateInMemoryData(incrementalDurations, aggregationTables, incrementalExecutorMap, siddhiAppContext, processedMetaStreamEvent, tableMap, windowMap, aggregationMap);
        IncrementalExecutor rootIncrementalExecutor = incrementalExecutorMap.get(incrementalDurations.get(0));
        rootIncrementalExecutor.setScheduler(scheduler);
        // Connect entry valve to root incremental executor
        entryValveExecutor.setNextExecutor(rootIncrementalExecutor);
        QueryParserHelper.initStreamRuntime(streamRuntime, incomingMetaStreamEvent, lockWrapper, aggregatorName);
        LatencyTracker latencyTrackerFind = null;
        LatencyTracker latencyTrackerInsert = null;
        ThroughputTracker throughputTrackerFind = null;
        ThroughputTracker throughputTrackerInsert = null;
        if (siddhiAppContext.getStatisticsManager() != null) {
            latencyTrackerFind = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            latencyTrackerInsert = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
            throughputTrackerFind = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            throughputTrackerInsert = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
        }
        streamRuntime.setCommonProcessor(new IncrementalAggregationProcessor(rootIncrementalExecutor, incomingExpressionExecutors, processedMetaStreamEvent, latencyTrackerInsert, throughputTrackerInsert, siddhiAppContext));
        List<ExpressionExecutor> baseExecutors = cloneExpressionExecutors(processExpressionExecutors);
        ExpressionExecutor timestampExecutor = baseExecutors.remove(0);
        return new AggregationRuntime(aggregationDefinition, incrementalExecutorMap, aggregationTables, ((SingleStreamRuntime) streamRuntime), entryValveExecutor, incrementalDurations, siddhiAppContext, baseExecutors, timestampExecutor, processedMetaStreamEvent, outputExpressionExecutors, latencyTrackerFind, throughputTrackerFind, recreateInMemoryData);
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, aggregationDefinition, siddhiAppContext);
        throw t;
    }
}
Also used : Variable(org.wso2.siddhi.query.api.expression.Variable) OutputAttribute(org.wso2.siddhi.query.api.execution.query.selection.OutputAttribute) Attribute(org.wso2.siddhi.query.api.definition.Attribute) Scheduler(org.wso2.siddhi.core.util.Scheduler) GroupByKeyGenerator(org.wso2.siddhi.core.query.selector.GroupByKeyGenerator) Element(org.wso2.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList) IncrementalExecutor(org.wso2.siddhi.core.aggregation.IncrementalExecutor) StreamEventPool(org.wso2.siddhi.core.event.stream.StreamEventPool) StreamRuntime(org.wso2.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) IncrementalAggregationProcessor(org.wso2.siddhi.core.aggregation.IncrementalAggregationProcessor) AggregationRuntime(org.wso2.siddhi.core.aggregation.AggregationRuntime) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ThroughputTracker(org.wso2.siddhi.core.util.statistics.ThroughputTracker) Table(org.wso2.siddhi.core.table.Table) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(org.wso2.siddhi.core.executor.ExpressionExecutor) StreamDefinition(org.wso2.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(org.wso2.siddhi.query.api.aggregation.TimePeriod) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) EntryValveExecutor(org.wso2.siddhi.core.query.input.stream.single.EntryValveExecutor) LockWrapper(org.wso2.siddhi.core.util.lock.LockWrapper) Expression(org.wso2.siddhi.query.api.expression.Expression) IncrementalAttributeAggregator(org.wso2.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) RecreateInMemoryData(org.wso2.siddhi.core.aggregation.RecreateInMemoryData) LatencyTracker(org.wso2.siddhi.core.util.statistics.LatencyTracker) MetaStreamEvent(org.wso2.siddhi.core.event.stream.MetaStreamEvent)

Example 2 with SiddhiAppRuntimeBuilder

use of org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder in project siddhi by wso2.

the class SiddhiManager method createSiddhiAppRuntime.

private SiddhiAppRuntime createSiddhiAppRuntime(SiddhiApp siddhiApp, String siddhiAppString) {
    SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder = SiddhiAppParser.parse(siddhiApp, siddhiAppString, siddhiContext);
    siddhiAppRuntimeBuilder.setSiddhiAppRuntimeMap(siddhiAppRuntimeMap);
    SiddhiAppRuntime siddhiAppRuntime = siddhiAppRuntimeBuilder.build();
    siddhiAppRuntimeMap.put(siddhiAppRuntime.getName(), siddhiAppRuntime);
    return siddhiAppRuntime;
}
Also used : SiddhiAppRuntimeBuilder(org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder)

Example 3 with SiddhiAppRuntimeBuilder

use of org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder in project siddhi by wso2.

the class AggregationParser method initDefaultTables.

private static HashMap<TimePeriod.Duration, Table> initDefaultTables(String aggregatorName, List<TimePeriod.Duration> durations, StreamDefinition streamDefinition, SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, List<Annotation> annotations, List<Variable> groupByVariableList) {
    HashMap<TimePeriod.Duration, Table> aggregationTableMap = new HashMap<>();
    // Create annotations for primary key
    Annotation primaryKeyAnnotation = new Annotation(SiddhiConstants.ANNOTATION_PRIMARY_KEY);
    primaryKeyAnnotation.element(null, "AGG_TIMESTAMP");
    for (Variable groupByVariable : groupByVariableList) {
        primaryKeyAnnotation.element(null, groupByVariable.getAttributeName());
    }
    annotations.add(primaryKeyAnnotation);
    for (TimePeriod.Duration duration : durations) {
        String tableId = aggregatorName + "_" + duration.toString();
        TableDefinition tableDefinition = TableDefinition.id(tableId);
        for (Attribute attribute : streamDefinition.getAttributeList()) {
            tableDefinition.attribute(attribute.getName(), attribute.getType());
        }
        annotations.forEach(tableDefinition::annotation);
        siddhiAppRuntimeBuilder.defineTable(tableDefinition);
        aggregationTableMap.put(duration, siddhiAppRuntimeBuilder.getTableMap().get(tableId));
    }
    return aggregationTableMap;
}
Also used : Table(org.wso2.siddhi.core.table.Table) Variable(org.wso2.siddhi.query.api.expression.Variable) HashMap(java.util.HashMap) OutputAttribute(org.wso2.siddhi.query.api.execution.query.selection.OutputAttribute) Attribute(org.wso2.siddhi.query.api.definition.Attribute) TimePeriod(org.wso2.siddhi.query.api.aggregation.TimePeriod) TableDefinition(org.wso2.siddhi.query.api.definition.TableDefinition) Annotation(org.wso2.siddhi.query.api.annotation.Annotation)

Example 4 with SiddhiAppRuntimeBuilder

use of org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder in project siddhi by wso2.

the class PartitionParser method parse.

public static PartitionRuntime parse(SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, Partition partition, SiddhiAppContext siddhiAppContext, ConcurrentMap<String, AbstractDefinition> streamDefinitionMap, int queryIndex) {
    PartitionRuntime partitionRuntime = new PartitionRuntime(siddhiAppRuntimeBuilder.getStreamDefinitionMap(), siddhiAppRuntimeBuilder.getStreamJunctions(), partition, siddhiAppContext);
    validateStreamPartitions(partition.getPartitionTypeMap(), streamDefinitionMap);
    for (Query query : partition.getQueryList()) {
        List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
        ConcurrentMap<String, AbstractDefinition> combinedStreamMap = new ConcurrentHashMap<String, AbstractDefinition>();
        combinedStreamMap.putAll(streamDefinitionMap);
        combinedStreamMap.putAll(partitionRuntime.getLocalStreamDefinitionMap());
        QueryRuntime queryRuntime = QueryParser.parse(query, siddhiAppContext, combinedStreamMap, siddhiAppRuntimeBuilder.getTableDefinitionMap(), siddhiAppRuntimeBuilder.getWindowDefinitionMap(), siddhiAppRuntimeBuilder.getAggregationDefinitionMap(), siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getAggregationMap(), siddhiAppRuntimeBuilder.getWindowMap(), siddhiAppRuntimeBuilder.getLockSynchronizer(), String.valueOf(queryIndex));
        queryIndex++;
        MetaStateEvent metaStateEvent = createMetaEventForPartitioner(queryRuntime.getMetaComplexEvent());
        partitionRuntime.addQuery(queryRuntime);
        partitionRuntime.addPartitionReceiver(queryRuntime, executors, metaStateEvent);
        QueryParserHelper.reduceMetaComplexEvent(metaStateEvent);
        if (queryRuntime.getMetaComplexEvent() instanceof MetaStateEvent) {
            QueryParserHelper.updateVariablePosition(metaStateEvent, executors);
        } else {
            QueryParserHelper.updateVariablePosition(metaStateEvent.getMetaStreamEvent(0), executors);
        }
        partitionRuntime.init();
    }
    return partitionRuntime;
}
Also used : Query(org.wso2.siddhi.query.api.execution.query.Query) QueryRuntime(org.wso2.siddhi.core.query.QueryRuntime) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) ArrayList(java.util.ArrayList) AbstractDefinition(org.wso2.siddhi.query.api.definition.AbstractDefinition) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PartitionRuntime(org.wso2.siddhi.core.partition.PartitionRuntime) MetaStateEvent(org.wso2.siddhi.core.event.state.MetaStateEvent)

Example 5 with SiddhiAppRuntimeBuilder

use of org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder in project siddhi by wso2.

the class SiddhiAppParser method parse.

/**
 * Parse an SiddhiApp returning SiddhiAppRuntime
 *
 * @param siddhiApp       plan to be parsed
 * @param siddhiAppString content of Siddhi application as string
 * @param siddhiContext   SiddhiContext  @return SiddhiAppRuntime
 *
 * @return SiddhiAppRuntimeBuilder
 */
public static SiddhiAppRuntimeBuilder parse(SiddhiApp siddhiApp, String siddhiAppString, SiddhiContext siddhiContext) {
    SiddhiAppContext siddhiAppContext = new SiddhiAppContext();
    siddhiAppContext.setSiddhiContext(siddhiContext);
    siddhiAppContext.setSiddhiAppString(siddhiAppString);
    try {
        Element element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_NAME, null, siddhiApp.getAnnotations());
        if (element != null) {
            siddhiAppContext.setName(element.getValue());
        } else {
            siddhiAppContext.setName(UUID.randomUUID().toString());
        }
        Annotation annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_ENFORCE_ORDER, siddhiApp.getAnnotations());
        if (annotation != null) {
            siddhiAppContext.setEnforceOrder(true);
        }
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_ASYNC, siddhiApp.getAnnotations());
        if (annotation != null) {
            throw new SiddhiAppCreationException("@Async not supported in SiddhiApp level, " + "instead use @Async with streams", annotation.getQueryContextStartIndex(), annotation.getQueryContextEndIndex());
        }
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_STATISTICS, siddhiApp.getAnnotations());
        List<Element> statisticsElements = new ArrayList<>();
        if (annotation != null) {
            statisticsElements = annotation.getElements();
        }
        if (siddhiContext.getStatisticsConfiguration() != null) {
            siddhiAppContext.setStatisticsManager(siddhiContext.getStatisticsConfiguration().getFactory().createStatisticsManager(siddhiContext.getStatisticsConfiguration().getMetricPrefix(), siddhiAppContext.getName(), statisticsElements));
        }
        Element statStateEnableElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, SiddhiConstants.ANNOTATION_ELEMENT_ENABLE, siddhiApp.getAnnotations());
        if (statStateEnableElement != null && Boolean.valueOf(statStateEnableElement.getValue())) {
            siddhiAppContext.setStatsEnabled(true);
        } else {
            Element statStateElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, null, siddhiApp.getAnnotations());
            // where sp uses @app:statistics('true').
            if (annotation != null && (statStateElement == null || Boolean.valueOf(statStateElement.getValue()))) {
                siddhiAppContext.setStatsEnabled(true);
            }
        }
        Element statStateIncludElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, SiddhiConstants.ANNOTATION_ELEMENT_INCLUDE, siddhiApp.getAnnotations());
        siddhiAppContext.setIncludedMetrics(generateIncludedMetrics(statStateIncludElement));
        siddhiAppContext.setThreadBarrier(new ThreadBarrier());
        siddhiAppContext.setExecutorService(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Siddhi-" + siddhiAppContext.getName() + "-executor-thread-%d").build()));
        siddhiAppContext.setScheduledExecutorService(Executors.newScheduledThreadPool(5, new ThreadFactoryBuilder().setNameFormat("Siddhi-" + siddhiAppContext.getName() + "-scheduler-thread-%d").build()));
        // Select the TimestampGenerator based on playback mode on/off
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_PLAYBACK, siddhiApp.getAnnotations());
        if (annotation != null) {
            String idleTime = null;
            String increment = null;
            EventTimeBasedMillisTimestampGenerator timestampGenerator = new EventTimeBasedMillisTimestampGenerator(siddhiAppContext.getScheduledExecutorService());
            // Get the optional elements of playback annotation
            for (Element e : annotation.getElements()) {
                if (SiddhiConstants.ANNOTATION_ELEMENT_IDLE_TIME.equalsIgnoreCase(e.getKey())) {
                    idleTime = e.getValue();
                } else if (SiddhiConstants.ANNOTATION_ELEMENT_INCREMENT.equalsIgnoreCase(e.getKey())) {
                    increment = e.getValue();
                } else {
                    throw new SiddhiAppValidationException("Playback annotation accepts only idle.time and " + "increment but found " + e.getKey());
                }
            }
            // idleTime and increment are optional but if one presents, the other also should be given
            if (idleTime != null && increment == null) {
                throw new SiddhiAppValidationException("Playback annotation requires both idle.time and " + "increment but increment not found");
            } else if (idleTime == null && increment != null) {
                throw new SiddhiAppValidationException("Playback annotation requires both idle.time and " + "increment but idle.time does not found");
            } else if (idleTime != null) {
                // The fourth case idleTime == null && increment == null are ignored because it means no heartbeat.
                try {
                    timestampGenerator.setIdleTime(SiddhiCompiler.parseTimeConstantDefinition(idleTime).value());
                } catch (SiddhiParserException ex) {
                    throw new SiddhiParserException("Invalid idle.time constant '" + idleTime + "' in playback " + "annotation", ex);
                }
                try {
                    timestampGenerator.setIncrementInMilliseconds(SiddhiCompiler.parseTimeConstantDefinition(increment).value());
                } catch (SiddhiParserException ex) {
                    throw new SiddhiParserException("Invalid increment constant '" + increment + "' in playback " + "annotation", ex);
                }
            }
            siddhiAppContext.setTimestampGenerator(timestampGenerator);
            siddhiAppContext.setPlayback(true);
        } else {
            siddhiAppContext.setTimestampGenerator(new SystemCurrentTimeMillisTimestampGenerator());
        }
        siddhiAppContext.setSnapshotService(new SnapshotService(siddhiAppContext));
        siddhiAppContext.setPersistenceService(new PersistenceService(siddhiAppContext));
        siddhiAppContext.setElementIdGenerator(new ElementIdGenerator(siddhiAppContext.getName()));
    } catch (DuplicateAnnotationException e) {
        throw new DuplicateAnnotationException(e.getMessageWithOutContext() + " for the same Siddhi app " + siddhiApp.toString(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
    }
    SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder = new SiddhiAppRuntimeBuilder(siddhiAppContext);
    defineStreamDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getStreamDefinitionMap(), siddhiAppContext);
    defineTableDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getTableDefinitionMap(), siddhiAppContext);
    defineWindowDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getWindowDefinitionMap(), siddhiAppContext);
    defineFunctionDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getFunctionDefinitionMap(), siddhiAppContext);
    defineAggregationDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getAggregationDefinitionMap(), siddhiAppContext);
    for (Window window : siddhiAppRuntimeBuilder.getWindowMap().values()) {
        try {
            window.init(siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getWindowMap(), window.getWindowDefinition().getId());
        } catch (Throwable t) {
            ExceptionUtil.populateQueryContext(t, window.getWindowDefinition(), siddhiAppContext);
            throw t;
        }
    }
    int queryIndex = 1;
    for (ExecutionElement executionElement : siddhiApp.getExecutionElementList()) {
        if (executionElement instanceof Query) {
            try {
                QueryRuntime queryRuntime = QueryParser.parse((Query) executionElement, siddhiAppContext, siddhiAppRuntimeBuilder.getStreamDefinitionMap(), siddhiAppRuntimeBuilder.getTableDefinitionMap(), siddhiAppRuntimeBuilder.getWindowDefinitionMap(), siddhiAppRuntimeBuilder.getAggregationDefinitionMap(), siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getAggregationMap(), siddhiAppRuntimeBuilder.getWindowMap(), siddhiAppRuntimeBuilder.getLockSynchronizer(), String.valueOf(queryIndex));
                siddhiAppRuntimeBuilder.addQuery(queryRuntime);
                queryIndex++;
            } catch (Throwable t) {
                ExceptionUtil.populateQueryContext(t, (Query) executionElement, siddhiAppContext);
                throw t;
            }
        } else {
            try {
                PartitionRuntime partitionRuntime = PartitionParser.parse(siddhiAppRuntimeBuilder, (Partition) executionElement, siddhiAppContext, siddhiAppRuntimeBuilder.getStreamDefinitionMap(), queryIndex);
                siddhiAppRuntimeBuilder.addPartition(partitionRuntime);
                siddhiAppContext.getSnapshotService().addSnapshotable("partition", partitionRuntime);
                queryIndex += ((Partition) executionElement).getQueryList().size();
            } catch (Throwable t) {
                ExceptionUtil.populateQueryContext(t, (Partition) executionElement, siddhiAppContext);
                throw t;
            }
        }
    }
    // Done last as they have to be started last
    defineTriggerDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getTriggerDefinitionMap(), siddhiAppContext);
    return siddhiAppRuntimeBuilder;
}
Also used : Query(org.wso2.siddhi.query.api.execution.query.Query) Element(org.wso2.siddhi.query.api.annotation.Element) ExecutionElement(org.wso2.siddhi.query.api.execution.ExecutionElement) ArrayList(java.util.ArrayList) ElementIdGenerator(org.wso2.siddhi.core.util.ElementIdGenerator) EventTimeBasedMillisTimestampGenerator(org.wso2.siddhi.core.util.timestamp.EventTimeBasedMillisTimestampGenerator) ThreadBarrier(org.wso2.siddhi.core.util.ThreadBarrier) QueryRuntime(org.wso2.siddhi.core.query.QueryRuntime) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Window(org.wso2.siddhi.core.window.Window) SnapshotService(org.wso2.siddhi.core.util.snapshot.SnapshotService) Partition(org.wso2.siddhi.query.api.execution.partition.Partition) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) SiddhiAppValidationException(org.wso2.siddhi.query.api.exception.SiddhiAppValidationException) Annotation(org.wso2.siddhi.query.api.annotation.Annotation) PersistenceService(org.wso2.siddhi.core.util.persistence.PersistenceService) SiddhiAppRuntimeBuilder(org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder) DuplicateAnnotationException(org.wso2.siddhi.query.api.exception.DuplicateAnnotationException) SiddhiParserException(org.wso2.siddhi.query.compiler.exception.SiddhiParserException) ExecutionElement(org.wso2.siddhi.query.api.execution.ExecutionElement) SystemCurrentTimeMillisTimestampGenerator(org.wso2.siddhi.core.util.timestamp.SystemCurrentTimeMillisTimestampGenerator) SiddhiAppContext(org.wso2.siddhi.core.config.SiddhiAppContext) PartitionRuntime(org.wso2.siddhi.core.partition.PartitionRuntime)

Aggregations

ArrayList (java.util.ArrayList)3 SiddhiAppCreationException (org.wso2.siddhi.core.exception.SiddhiAppCreationException)2 VariableExpressionExecutor (org.wso2.siddhi.core.executor.VariableExpressionExecutor)2 PartitionRuntime (org.wso2.siddhi.core.partition.PartitionRuntime)2 QueryRuntime (org.wso2.siddhi.core.query.QueryRuntime)2 Table (org.wso2.siddhi.core.table.Table)2 SiddhiAppRuntimeBuilder (org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder)2 TimePeriod (org.wso2.siddhi.query.api.aggregation.TimePeriod)2 Annotation (org.wso2.siddhi.query.api.annotation.Annotation)2 Element (org.wso2.siddhi.query.api.annotation.Element)2 Attribute (org.wso2.siddhi.query.api.definition.Attribute)2 Query (org.wso2.siddhi.query.api.execution.query.Query)2 OutputAttribute (org.wso2.siddhi.query.api.execution.query.selection.OutputAttribute)2 Variable (org.wso2.siddhi.query.api.expression.Variable)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 HashMap (java.util.HashMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ReentrantLock (java.util.concurrent.locks.ReentrantLock)1 AggregationRuntime (org.wso2.siddhi.core.aggregation.AggregationRuntime)1 IncrementalAggregationProcessor (org.wso2.siddhi.core.aggregation.IncrementalAggregationProcessor)1