use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.
the class SnapshotableEventQueueTestCase method incrementalPersistenceTest2.
@Test
public void incrementalPersistenceTest2() throws InterruptedException, IOException, ClassNotFoundException {
MetaStreamEvent metaStreamEvent = new MetaStreamEvent();
metaStreamEvent.addOutputData(new Attribute("symbol", Attribute.Type.STRING));
metaStreamEvent.addOutputData(new Attribute("price", Attribute.Type.FLOAT));
metaStreamEvent.addOutputData(new Attribute("volume", Attribute.Type.LONG));
StreamEventCloner streamEventCloner = new StreamEventCloner(metaStreamEvent, new StreamEventFactory(metaStreamEvent));
SnapshotableStreamEventQueue snapshotableStreamEventQueue = new SnapshotableStreamEventQueue(new StreamEventClonerHolder(streamEventCloner));
StreamEvent streamEvent = new StreamEvent(metaStreamEvent.getBeforeWindowData().size(), metaStreamEvent.getOnAfterWindowData().size(), metaStreamEvent.getOutputData().size());
streamEvent.setOutputData(new Object[] { "IBM", 500.6f, 1 });
for (int i = 0; i < 10; i++) {
streamEvent.getOutputData()[2] = i;
snapshotableStreamEventQueue.add(streamEventCloner.copyStreamEvent(streamEvent));
}
HashMap<Long, String> snapshots = new HashMap<>();
Snapshot snapshot1 = snapshotableStreamEventQueue.getSnapshot();
StreamEvent streamEvents = (StreamEvent) snapshot1.getState();
Assert.assertTrue(streamEvents != null);
snapshots.put(3L, toString(snapshot1));
for (int i = 7; i < 10; i++) {
snapshotableStreamEventQueue.next();
snapshotableStreamEventQueue.remove();
}
Snapshot snapshot2 = snapshotableStreamEventQueue.getSnapshot();
ArrayList<Operation> operationLog = (ArrayList<Operation>) snapshot2.getState();
Assert.assertTrue(operationLog != null);
snapshots.put(4L, toString(snapshot2));
for (int i = 10; i < 15; i++) {
streamEvent.getOutputData()[2] = i;
snapshotableStreamEventQueue.add(streamEventCloner.copyStreamEvent(streamEvent));
}
Snapshot snapshot3 = snapshotableStreamEventQueue.getSnapshot();
operationLog = (ArrayList<Operation>) snapshot3.getState();
Assert.assertTrue(operationLog != null);
snapshots.put(5L, toString(snapshot3));
SnapshotableStreamEventQueue snapshotableStreamEventQueue2 = new SnapshotableStreamEventQueue(new StreamEventClonerHolder(streamEventCloner));
SnapshotStateList snapshotStateList = new SnapshotStateList();
for (Map.Entry<Long, String> entry : snapshots.entrySet()) {
snapshotStateList.putSnapshotState(entry.getKey(), (Snapshot) fromString(entry.getValue()));
}
snapshotableStreamEventQueue2.restore(snapshotStateList);
Assert.assertEquals(snapshotableStreamEventQueue, snapshotableStreamEventQueue2);
}
use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.
the class EventTestCase method testQueryParser.
@Test
public void testQueryParser() {
StreamDefinition streamDefinition = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT);
StreamDefinition outStreamDefinition = StreamDefinition.id("outputStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT);
Query query = new Query();
query.annotation(Annotation.annotation("info").element("name", "query1"));
query.from(InputStream.stream("cseEventStream").filter(Expression.compare(Expression.variable("volume"), Compare.Operator.NOT_EQUAL, Expression.value(50))));
query.select(Selector.selector().select("symbol", Expression.variable("symbol")).select("price", Expression.variable("price")));
query.insertInto("outputStream");
Map<String, AbstractDefinition> tableDefinitionMap = new HashMap<>();
Map<String, AbstractDefinition> windowDefinitionMap = new HashMap<>();
Map<String, AbstractDefinition> aggregationDefinitionMap = new HashMap<>();
Map<String, Table> tableMap = new HashMap<String, Table>();
Map<String, Window> eventWindowMap = new HashMap<String, Window>();
Map<String, AggregationRuntime> aggregationMap = new HashMap<String, AggregationRuntime>();
Map<String, List<Source>> eventSourceMap = new HashMap<String, List<Source>>();
Map<String, List<Sink>> eventSinkMap = new HashMap<String, List<Sink>>();
Map<String, AbstractDefinition> streamDefinitionMap = new HashMap<String, AbstractDefinition>();
LockSynchronizer lockSynchronizer = new LockSynchronizer();
streamDefinitionMap.put("cseEventStream", streamDefinition);
streamDefinitionMap.put("outputStream", outStreamDefinition);
SiddhiContext siddhicontext = new SiddhiContext();
SiddhiAppContext context = new SiddhiAppContext();
context.setSiddhiContext(siddhicontext);
context.setIdGenerator(new IdGenerator());
context.setSnapshotService(new SnapshotService(context));
QueryRuntimeImpl runtime = QueryParser.parse(query, context, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, aggregationMap, eventWindowMap, lockSynchronizer, "1", false, SiddhiConstants.PARTITION_ID_DEFAULT);
AssertJUnit.assertNotNull(runtime);
AssertJUnit.assertTrue(runtime.getStreamRuntime() instanceof SingleStreamRuntime);
AssertJUnit.assertNotNull(runtime.getSelector());
AssertJUnit.assertTrue(runtime.getMetaComplexEvent() instanceof MetaStreamEvent);
}
use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.
the class AggregationRuntime method compileExpression.
public CompiledCondition compileExpression(Expression expression, Within within, Expression per, List<Variable> queryGroupByList, MatchingMetaInfoHolder matchingMetaInfoHolder, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, SiddhiQueryContext siddhiQueryContext) {
String aggregationName = aggregationDefinition.getId();
boolean isOptimisedTableLookup = isOptimisedLookup;
Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions = new HashMap<>();
CompiledCondition withinInMemoryCompileCondition;
CompiledCondition onCompiledCondition;
List<Attribute> additionalAttributes = new ArrayList<>();
// Define additional attribute list
additionalAttributes.add(new Attribute("_START", Attribute.Type.LONG));
additionalAttributes.add(new Attribute("_END", Attribute.Type.LONG));
int lowerGranularitySize = this.activeIncrementalDurations.size() - 1;
List<String> lowerGranularityAttributes = new ArrayList<>();
if (isDistributed) {
// for values calculated in in-memory in the shards
for (int i = 0; i < lowerGranularitySize; i++) {
String attributeName = "_AGG_TIMESTAMP_FILTER_" + i;
additionalAttributes.add(new Attribute(attributeName, Attribute.Type.LONG));
lowerGranularityAttributes.add(attributeName);
}
}
// Get table definition. Table definitions for all the tables used to persist aggregates are similar.
// Therefore it's enough to get the definition from one table.
AbstractDefinition tableDefinition = aggregationTables.get(activeIncrementalDurations.get(0)).getTableDefinition();
boolean isOnDemandQuery = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length == 1;
// Alter existing meta stream event or create new one if a meta stream doesn't exist
// After calling this method the original MatchingMetaInfoHolder's meta stream event would be altered
// Alter meta info holder to contain stream event and aggregate both when it's a on-demand query
MetaStreamEvent metaStreamEventForTableLookups;
if (isOnDemandQuery) {
metaStreamEventForTableLookups = alterMetaStreamEvent(true, new MetaStreamEvent(), additionalAttributes);
matchingMetaInfoHolder = alterMetaInfoHolderForOnDemandQuery(metaStreamEventForTableLookups, matchingMetaInfoHolder);
} else {
metaStreamEventForTableLookups = alterMetaStreamEvent(false, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(0), additionalAttributes);
}
// Create new MatchingMetaInfoHolder containing newMetaStreamEventWithStartEnd and table meta event
String aggReferenceId = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(1).getInputReferenceId();
String referenceName = aggReferenceId == null ? aggregationName : aggReferenceId;
MetaStreamEvent metaStoreEventForTableLookups = createMetaStoreEvent(tableDefinition, referenceName);
// Create new MatchingMetaInfoHolder containing metaStreamEventForTableLookups and table meta event
MatchingMetaInfoHolder metaInfoHolderForTableLookups = createNewStreamTableMetaInfoHolder(metaStreamEventForTableLookups, metaStoreEventForTableLookups);
// Create per expression executor
ExpressionExecutor perExpressionExecutor;
if (per != null) {
perExpressionExecutor = ExpressionParser.parseExpression(per, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
if (perExpressionExecutor.getReturnType() != Attribute.Type.STRING) {
throw new SiddhiAppCreationException("Query " + siddhiQueryContext.getName() + "'s per value expected a string but found " + perExpressionExecutor.getReturnType(), per.getQueryContextStartIndex(), per.getQueryContextEndIndex());
}
// Additional Per time function verification at compile time if it is a constant
if (perExpressionExecutor instanceof ConstantExpressionExecutor) {
String perValue = ((ConstantExpressionExecutor) perExpressionExecutor).getValue().toString();
try {
normalizeDuration(perValue);
} catch (SiddhiAppValidationException e) {
throw new SiddhiAppValidationException("Aggregation Query's per value is expected to be of a valid time function of the " + "following " + TimePeriod.Duration.SECONDS + ", " + TimePeriod.Duration.MINUTES + ", " + TimePeriod.Duration.HOURS + ", " + TimePeriod.Duration.DAYS + ", " + TimePeriod.Duration.MONTHS + ", " + TimePeriod.Duration.YEARS + ".");
}
}
} else {
throw new SiddhiAppCreationException("Syntax Error: Aggregation join query must contain a `per` " + "definition for granularity");
}
// Create start and end time expression
Expression startEndTimeExpression;
ExpressionExecutor startTimeEndTimeExpressionExecutor;
if (within != null) {
if (within.getTimeRange().size() == 1) {
startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0));
} else {
// within.getTimeRange().size() == 2
startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0), within.getTimeRange().get(1));
}
startTimeEndTimeExpressionExecutor = ExpressionParser.parseExpression(startEndTimeExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
} else {
throw new SiddhiAppCreationException("Syntax Error : Aggregation read query must contain a `within` " + "definition for filtering of aggregation data.");
}
// Create within expression
Expression timeFilterExpression;
if (isProcessingOnExternalTime) {
timeFilterExpression = Expression.variable(AGG_EXTERNAL_TIMESTAMP_COL);
} else {
timeFilterExpression = Expression.variable(AGG_START_TIMESTAMP_COL);
}
Expression withinExpression;
Expression start = Expression.variable(additionalAttributes.get(0).getName());
Expression end = Expression.variable(additionalAttributes.get(1).getName());
Expression compareWithStartTime = Compare.compare(start, Compare.Operator.LESS_THAN_EQUAL, timeFilterExpression);
Expression compareWithEndTime = Compare.compare(timeFilterExpression, Compare.Operator.LESS_THAN, end);
withinExpression = Expression.and(compareWithStartTime, compareWithEndTime);
List<ExpressionExecutor> timestampFilterExecutors = new ArrayList<>();
if (isDistributed) {
for (int i = 0; i < lowerGranularitySize; i++) {
Expression[] expressionArray = new Expression[] { new AttributeFunction("", "currentTimeMillis", null), Expression.value(this.activeIncrementalDurations.get(i + 1).toString()) };
Expression filterExpression = new AttributeFunction("incrementalAggregator", "getAggregationStartTime", expressionArray);
timestampFilterExecutors.add(ExpressionParser.parseExpression(filterExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext));
}
}
// Create compile condition per each table used to persist aggregates.
// These compile conditions are used to check whether the aggregates in tables are within the given duration.
// Combine with and on condition for table query
boolean shouldApplyReducedCondition = false;
Expression reducedExpression = null;
// Check if there is no on conditions
if (!(expression instanceof BoolConstant)) {
// For abstract queryable table
AggregationExpressionBuilder aggregationExpressionBuilder = new AggregationExpressionBuilder(expression);
AggregationExpressionVisitor expressionVisitor = new AggregationExpressionVisitor(metaStreamEventForTableLookups.getInputReferenceId(), metaStreamEventForTableLookups.getLastInputDefinition().getAttributeList(), this.tableAttributesNameList);
aggregationExpressionBuilder.build(expressionVisitor);
shouldApplyReducedCondition = expressionVisitor.applyReducedExpression();
reducedExpression = expressionVisitor.getReducedExpression();
}
Expression withinExpressionTable;
if (shouldApplyReducedCondition) {
withinExpressionTable = Expression.and(withinExpression, reducedExpression);
} else {
withinExpressionTable = withinExpression;
}
List<Variable> queryGroupByListCopy = new ArrayList<>(queryGroupByList);
Variable timestampVariable = new Variable(AGG_START_TIMESTAMP_COL);
List<String> queryGroupByNamesList = queryGroupByListCopy.stream().map(Variable::getAttributeName).collect(Collectors.toList());
boolean queryGroupByContainsTimestamp = queryGroupByNamesList.remove(AGG_START_TIMESTAMP_COL);
boolean isQueryGroupBySameAsAggGroupBy = queryGroupByListCopy.isEmpty() || (queryGroupByListCopy.contains(timestampVariable) && queryGroupByNamesList.equals(groupByVariablesList));
List<VariableExpressionExecutor> variableExpExecutorsForTableLookups = new ArrayList<>();
Map<TimePeriod.Duration, CompiledSelection> withinTableCompiledSelection = new HashMap<>();
if (isOptimisedTableLookup) {
Selector selector = Selector.selector();
List<Variable> groupByList = new ArrayList<>();
if (!isQueryGroupBySameAsAggGroupBy) {
if (queryGroupByContainsTimestamp) {
if (isProcessingOnExternalTime) {
groupByList.add(new Variable(AGG_EXTERNAL_TIMESTAMP_COL));
} else {
groupByList.add(new Variable(AGG_START_TIMESTAMP_COL));
}
// Remove timestamp to process the rest
queryGroupByListCopy.remove(timestampVariable);
}
for (Variable queryGroupBy : queryGroupByListCopy) {
String referenceId = queryGroupBy.getStreamId();
if (referenceId == null) {
if (tableAttributesNameList.contains(queryGroupBy.getAttributeName())) {
groupByList.add(queryGroupBy);
}
} else if (referenceId.equalsIgnoreCase(referenceName)) {
groupByList.add(queryGroupBy);
}
}
// If query group bys are based on joining stream
if (groupByList.isEmpty()) {
isQueryGroupBySameAsAggGroupBy = true;
}
}
groupByList.forEach((groupBy) -> groupBy.setStreamId(referenceName));
selector.addGroupByList(groupByList);
List<OutputAttribute> selectorList;
if (!isQueryGroupBySameAsAggGroupBy) {
selectorList = constructSelectorList(isProcessingOnExternalTime, isDistributed, isLatestEventColAdded, baseAggregatorBeginIndex, groupByVariablesList.size(), finalBaseExpressionsList, tableDefinition, groupByList);
} else {
selectorList = defaultSelectorList;
}
for (OutputAttribute outputAttribute : selectorList) {
if (outputAttribute.getExpression() instanceof Variable) {
((Variable) outputAttribute.getExpression()).setStreamId(referenceName);
} else {
for (Expression parameter : ((AttributeFunction) outputAttribute.getExpression()).getParameters()) {
((Variable) parameter).setStreamId(referenceName);
}
}
}
selector.addSelectionList(selectorList);
try {
aggregationTables.entrySet().forEach((durationTableEntry -> {
CompiledSelection compiledSelection = ((QueryableProcessor) durationTableEntry.getValue()).compileSelection(selector, tableDefinition.getAttributeList(), metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
withinTableCompiledSelection.put(durationTableEntry.getKey(), compiledSelection);
}));
} catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Aggregation Query optimization failed for aggregation: '" + aggregationName + "'. " + "Creating table lookup query in normal mode. Reason for failure: " + e.getMessage(), e);
}
isOptimisedTableLookup = false;
}
}
for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) {
CompiledCondition withinTableCompileCondition = entry.getValue().compileCondition(withinExpressionTable, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
withinTableCompiledConditions.put(entry.getKey(), withinTableCompileCondition);
}
// Create compile condition for in-memory data.
// This compile condition is used to check whether the running aggregates (in-memory data)
// are within given duration
withinInMemoryCompileCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), withinExpression, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
// Create compile condition for in-memory data, in case of distributed
// Look at the lower level granularities
Map<TimePeriod.Duration, CompiledCondition> withinTableLowerGranularityCompileCondition = new HashMap<>();
Expression lowerGranularity;
if (isDistributed) {
for (int i = 0; i < lowerGranularitySize; i++) {
if (isProcessingOnExternalTime) {
lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), withinExpressionTable);
} else {
if (shouldApplyReducedCondition) {
lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), reducedExpression);
} else {
lowerGranularity = Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i)));
}
}
TimePeriod.Duration duration = this.activeIncrementalDurations.get(i);
String tableName = aggregationName + "_" + duration.toString();
CompiledCondition compiledCondition = tableMap.get(tableName).compileCondition(lowerGranularity, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
withinTableLowerGranularityCompileCondition.put(duration, compiledCondition);
}
}
QueryParserHelper.reduceMetaComplexEvent(metaInfoHolderForTableLookups.getMetaStateEvent());
// On compile condition.
// After finding all the aggregates belonging to within duration, the final on condition (given as
// "on stream1.name == aggregator.nickName ..." in the join query) must be executed on that data.
// This condition is used for that purpose.
onCompiledCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), expression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, siddhiQueryContext);
return new IncrementalAggregateCompileCondition(isOnDemandQuery, aggregationName, isProcessingOnExternalTime, isDistributed, activeIncrementalDurations, aggregationTables, outputExpressionExecutors, isOptimisedTableLookup, withinTableCompiledSelection, withinTableCompiledConditions, withinInMemoryCompileCondition, withinTableLowerGranularityCompileCondition, onCompiledCondition, additionalAttributes, perExpressionExecutor, startTimeEndTimeExpressionExecutor, timestampFilterExecutors, aggregateMetaSteamEvent, matchingMetaInfoHolder, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups);
}
use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.
the class QueryParser method parse.
/**
* Parse a query and return corresponding QueryRuntime.
*
* @param query query to be parsed.
* @param siddhiAppContext associated Siddhi app context.
* @param streamDefinitionMap keyvalue containing user given stream definitions.
* @param tableDefinitionMap keyvalue containing table definitions.
* @param windowDefinitionMap keyvalue containing window definition map.
* @param aggregationDefinitionMap keyvalue containing aggregation definition map.
* @param tableMap keyvalue containing event tables.
* @param aggregationMap keyvalue containing aggrigation runtimes.
* @param windowMap keyvalue containing event window map.
* @param lockSynchronizer Lock synchronizer for sync the lock across queries.
* @param queryIndex query index to identify unknown query by number
* @param partitioned is the query partitioned
* @param partitionId The ID of the partition
* @return queryRuntime
*/
public static QueryRuntimeImpl parse(Query query, SiddhiAppContext siddhiAppContext, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, AggregationRuntime> aggregationMap, Map<String, Window> windowMap, LockSynchronizer lockSynchronizer, String queryIndex, boolean partitioned, String partitionId) {
List<VariableExpressionExecutor> executors = new ArrayList<>();
QueryRuntimeImpl queryRuntime;
Element nameElement = null;
LatencyTracker latencyTracker = null;
LockWrapper lockWrapper = null;
try {
nameElement = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
String queryName;
if (nameElement != null) {
queryName = nameElement.getValue();
} else {
queryName = "query_" + queryIndex;
}
SiddhiQueryContext siddhiQueryContext = new SiddhiQueryContext(siddhiAppContext, queryName, partitionId);
siddhiQueryContext.setPartitioned(partitioned);
latencyTracker = QueryParserHelper.createLatencyTracker(siddhiAppContext, siddhiQueryContext.getName(), SiddhiConstants.METRIC_INFIX_QUERIES, null);
siddhiQueryContext.setLatencyTracker(latencyTracker);
OutputStream.OutputEventType outputEventType = query.getOutputStream().getOutputEventType();
if (query.getOutputRate() != null && query.getOutputRate() instanceof SnapshotOutputRate) {
if (outputEventType != OutputStream.OutputEventType.ALL_EVENTS) {
throw new SiddhiAppCreationException("As query '" + siddhiQueryContext.getName() + "' is performing snapshot rate limiting, it can only insert '" + OutputStream.OutputEventType.ALL_EVENTS + "' but it is inserting '" + outputEventType + "'!", query.getOutputStream().getQueryContextStartIndex(), query.getOutputStream().getQueryContextEndIndex());
}
}
siddhiQueryContext.setOutputEventType(outputEventType);
boolean outputExpectsExpiredEvents = false;
if (outputEventType != OutputStream.OutputEventType.CURRENT_EVENTS) {
outputExpectsExpiredEvents = true;
}
StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(), query, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, outputExpectsExpiredEvents, siddhiQueryContext);
QuerySelector selector;
if (streamRuntime.getQuerySelector() != null) {
selector = streamRuntime.getQuerySelector();
} else {
selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), streamRuntime.getMetaComplexEvent(), tableMap, executors, SiddhiConstants.UNKNOWN_STATE, streamRuntime.getProcessingMode(), outputExpectsExpiredEvents, siddhiQueryContext);
}
boolean isWindow = query.getInputStream() instanceof JoinInputStream;
if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
if (streamHandler instanceof io.siddhi.query.api.execution.query.input.handler.Window) {
isWindow = true;
break;
}
}
}
Element synchronizedElement = AnnotationHelper.getAnnotationElement("synchronized", null, query.getAnnotations());
if (synchronizedElement != null) {
if (!("false".equalsIgnoreCase(synchronizedElement.getValue()))) {
// Query LockWrapper does not need a unique
lockWrapper = new LockWrapper("");
// id since it will
// not be passed to the LockSynchronizer.
// LockWrapper does not have a default lock
lockWrapper.setLock(new ReentrantLock());
}
} else {
if (isWindow || !(streamRuntime instanceof SingleStreamRuntime)) {
if (streamRuntime instanceof JoinStreamRuntime) {
// If at least one Window is involved in the join, use the LockWrapper of that window
// for the query as well.
// If join is between two EventWindows, sync the locks of the LockWrapper of those windows
// and use either of them for query.
MetaStateEvent metaStateEvent = (MetaStateEvent) streamRuntime.getMetaComplexEvent();
MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
if (metaStreamEvents[0].getEventType() == EventType.WINDOW && metaStreamEvents[1].getEventType() == EventType.WINDOW) {
LockWrapper leftLockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
LockWrapper rightLockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
if (!leftLockWrapper.equals(rightLockWrapper)) {
// Sync the lock across both wrappers
lockSynchronizer.sync(leftLockWrapper, rightLockWrapper);
}
// Can use either leftLockWrapper or rightLockWrapper since both of them will hold the
// same lock internally
// If either of their lock is updated later, the other lock also will be update by the
// LockSynchronizer.
lockWrapper = leftLockWrapper;
} else if (metaStreamEvents[0].getEventType() == EventType.WINDOW) {
// Share the same wrapper as the query lock wrapper
lockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
} else if (metaStreamEvents[1].getEventType() == EventType.WINDOW) {
// Share the same wrapper as the query lock wrapper
lockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
} else {
// Join does not contain any Window
// Query LockWrapper does not need a unique
lockWrapper = new LockWrapper("");
// id since
// it will not be passed to the LockSynchronizer.
// LockWrapper does not have a default lock
lockWrapper.setLock(new ReentrantLock());
}
} else {
lockWrapper = new LockWrapper("");
lockWrapper.setLock(new ReentrantLock());
}
}
}
OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(query.getOutputStream().getId(), query.getOutputRate(), query.getSelector().getGroupByList().size() != 0, isWindow, siddhiQueryContext);
if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
selector.setBatchingEnabled(false);
}
boolean groupBy = !query.getSelector().getGroupByList().isEmpty();
OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(), streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), tableMap, windowMap, !(streamRuntime instanceof SingleStreamRuntime) || groupBy, siddhiQueryContext);
QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent(), lockWrapper, siddhiQueryContext.getName());
// Update cache compile selection variable expression executors
if (streamRuntime instanceof JoinStreamRuntime) {
streamRuntime.getSingleStreamRuntimes().forEach((singleStreamRuntime -> {
Processor processorChain = singleStreamRuntime.getProcessorChain();
if (processorChain instanceof JoinProcessor) {
CompiledSelection compiledSelection = ((JoinProcessor) processorChain).getCompiledSelection();
if (compiledSelection instanceof AbstractQueryableRecordTable.CompiledSelectionWithCache) {
List<VariableExpressionExecutor> variableExpressionExecutors = ((AbstractQueryableRecordTable.CompiledSelectionWithCache) compiledSelection).getVariableExpressionExecutorsForQuerySelector();
QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), variableExpressionExecutors);
}
}
}));
}
selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
queryRuntime = new QueryRuntimeImpl(query, streamRuntime, selector, outputRateLimiter, outputCallback, streamRuntime.getMetaComplexEvent(), siddhiQueryContext);
if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
selector.setBatchingEnabled(false);
((WrappedSnapshotOutputRateLimiter) outputRateLimiter).init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(), selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
}
outputRateLimiter.init(lockWrapper, groupBy, siddhiQueryContext);
} catch (DuplicateDefinitionException e) {
if (nameElement != null) {
throw new DuplicateDefinitionException(e.getMessageWithOutContext() + ", when creating query " + nameElement.getValue(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
} else {
throw new DuplicateDefinitionException(e.getMessage(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
}
} catch (Throwable t) {
ExceptionUtil.populateQueryContext(t, query, siddhiAppContext);
throw t;
}
return queryRuntime;
}
use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.
the class SelectorParser method getAttributeProcessors.
/**
* Method to construct AttributeProcessor list for the selector.
*
* @param selector Selector
* @param id stream id
* @param metaComplexEvent meta ComplexEvent
* @param tableMap Table Map
* @param variableExpressionExecutors list of VariableExpressionExecutors
* @param outputStream output stream
* @param processingMode processing mode of the query
* @param outputExpectsExpiredEvents is expired events sent as output
* @param groupBy is Attributes groupBy
* @param siddhiQueryContext current siddhi query context @return list of AttributeProcessors
*/
private static List<AttributeProcessor> getAttributeProcessors(Selector selector, String id, MetaComplexEvent metaComplexEvent, Map<String, Table> tableMap, List<VariableExpressionExecutor> variableExpressionExecutors, OutputStream outputStream, int metaPosition, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, boolean groupBy, SiddhiQueryContext siddhiQueryContext) {
List<AttributeProcessor> attributeProcessorList = new ArrayList<>();
StreamDefinition outputDefinition = StreamDefinition.id(id);
outputDefinition.setQueryContextStartIndex(outputStream.getQueryContextStartIndex());
outputDefinition.setQueryContextEndIndex(outputStream.getQueryContextEndIndex());
List<OutputAttribute> outputAttributes = selector.getSelectionList();
if (selector.getSelectionList().size() == 0) {
if (metaComplexEvent instanceof MetaStreamEvent) {
List<Attribute> attributeList = ((MetaStreamEvent) metaComplexEvent).getLastInputDefinition().getAttributeList();
for (Attribute attribute : attributeList) {
Variable variable = new Variable(attribute.getName());
variable.setQueryContextStartIndex(selector.getQueryContextStartIndex());
variable.setQueryContextEndIndex(selector.getQueryContextEndIndex());
OutputAttribute outputAttribute = new OutputAttribute(variable);
outputAttribute.setQueryContextStartIndex(selector.getQueryContextStartIndex());
outputAttribute.setQueryContextEndIndex(selector.getQueryContextEndIndex());
outputAttributes.add(outputAttribute);
}
} else {
int position = 0;
for (MetaStreamEvent metaStreamEvent : ((MetaStateEvent) metaComplexEvent).getMetaStreamEvents()) {
if (metaPosition == SiddhiConstants.UNKNOWN_STATE || metaPosition == position) {
List<Attribute> attributeList = metaStreamEvent.getLastInputDefinition().getAttributeList();
for (Attribute attribute : attributeList) {
Variable variable = new Variable(attribute.getName());
variable.setQueryContextStartIndex(selector.getQueryContextStartIndex());
variable.setQueryContextEndIndex(selector.getQueryContextEndIndex());
OutputAttribute outputAttribute = new OutputAttribute(variable);
outputAttribute.setQueryContextStartIndex(selector.getQueryContextStartIndex());
outputAttribute.setQueryContextEndIndex(selector.getQueryContextEndIndex());
if (!outputAttributes.contains(outputAttribute)) {
outputAttributes.add(outputAttribute);
} else {
List<AbstractDefinition> definitions = new ArrayList<>();
for (MetaStreamEvent aMetaStreamEvent : ((MetaStateEvent) metaComplexEvent).getMetaStreamEvents()) {
definitions.add(aMetaStreamEvent.getLastInputDefinition());
}
throw new DuplicateAttributeException("Duplicate attribute exist in streams " + definitions, outputStream.getQueryContextStartIndex(), outputStream.getQueryContextEndIndex());
}
}
}
++position;
}
}
}
int i = 0;
for (OutputAttribute outputAttribute : outputAttributes) {
ExpressionExecutor expressionExecutor = ExpressionParser.parseExpression(outputAttribute.getExpression(), metaComplexEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, variableExpressionExecutors, groupBy, 0, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
if (expressionExecutor instanceof VariableExpressionExecutor) {
// for variables we will directly put
// value at conversion stage
VariableExpressionExecutor executor = ((VariableExpressionExecutor) expressionExecutor);
if (metaComplexEvent instanceof MetaStateEvent) {
((MetaStateEvent) metaComplexEvent).addOutputDataAllowingDuplicate(new MetaStateEventAttribute(executor.getAttribute(), executor.getPosition()));
} else {
((MetaStreamEvent) metaComplexEvent).addOutputDataAllowingDuplicate(executor.getAttribute());
}
outputDefinition.attribute(outputAttribute.getRename(), ((VariableExpressionExecutor) expressionExecutor).getAttribute().getType());
} else {
// To maintain output variable positions
if (metaComplexEvent instanceof MetaStateEvent) {
((MetaStateEvent) metaComplexEvent).addOutputDataAllowingDuplicate(null);
} else {
((MetaStreamEvent) metaComplexEvent).addOutputDataAllowingDuplicate(null);
}
AttributeProcessor attributeProcessor = new AttributeProcessor(expressionExecutor);
attributeProcessor.setOutputPosition(i);
attributeProcessorList.add(attributeProcessor);
outputDefinition.attribute(outputAttribute.getRename(), attributeProcessor.getOutputType());
}
i++;
}
metaComplexEvent.setOutputDefinition(outputDefinition);
return attributeProcessorList;
}
Aggregations