use of io.siddhi.core.query.QueryRuntimeImpl 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.query.QueryRuntimeImpl 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.query.QueryRuntimeImpl in project siddhi by wso2.
the class PartitionParser method parse.
public static PartitionRuntimeImpl parse(SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, Partition partition, SiddhiAppContext siddhiAppContext, int queryIndex, int partitionIndex) {
ConcurrentMap<String, AbstractDefinition> streamDefinitionMap = siddhiAppRuntimeBuilder.getStreamDefinitionMap();
ConcurrentMap<String, AbstractDefinition> windowDefinitionMap = siddhiAppRuntimeBuilder.getWindowDefinitionMap();
validateStreamPartitions(partition.getPartitionTypeMap(), streamDefinitionMap, windowDefinitionMap);
PartitionRuntimeImpl partitionRuntime = new PartitionRuntimeImpl(streamDefinitionMap, windowDefinitionMap, siddhiAppRuntimeBuilder.getStreamJunctions(), partition, partitionIndex, siddhiAppContext);
for (Query query : partition.getQueryList()) {
List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
ConcurrentMap<String, AbstractDefinition> combinedStreamMap = new ConcurrentHashMap<String, AbstractDefinition>();
combinedStreamMap.putAll(streamDefinitionMap);
combinedStreamMap.putAll(windowDefinitionMap);
combinedStreamMap.putAll(partitionRuntime.getLocalStreamDefinitionMap());
QueryRuntimeImpl queryRuntime = QueryParser.parse(query, siddhiAppContext, combinedStreamMap, siddhiAppRuntimeBuilder.getTableDefinitionMap(), siddhiAppRuntimeBuilder.getWindowDefinitionMap(), siddhiAppRuntimeBuilder.getAggregationDefinitionMap(), siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getAggregationMap(), siddhiAppRuntimeBuilder.getWindowMap(), siddhiAppRuntimeBuilder.getLockSynchronizer(), String.valueOf(queryIndex), true, partitionRuntime.getPartitionName());
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;
}
use of io.siddhi.core.query.QueryRuntimeImpl in project siddhi by wso2.
the class PartitionRuntimeImpl method initPartition.
public void initPartition() {
PartitionState state = stateHolder.getState();
try {
Long time = state.partitionKeys.get(SiddhiAppContext.getPartitionFlowId());
if (time == null) {
synchronized (state) {
time = state.partitionKeys.get(SiddhiAppContext.getPartitionFlowId());
if (time == null) {
for (QueryRuntime queryRuntime : queryRuntimeList) {
((QueryRuntimeImpl) queryRuntime).initPartition();
}
}
state.partitionKeys.put(SiddhiAppContext.getPartitionFlowId(), siddhiAppContext.getTimestampGenerator().currentTime());
}
} else {
state.partitionKeys.put(SiddhiAppContext.getPartitionFlowId(), siddhiAppContext.getTimestampGenerator().currentTime());
}
} finally {
stateHolder.returnState(state);
}
if (purgingEnabled) {
siddhiAppContext.getScheduledExecutorService().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
long currentTime = siddhiAppContext.getTimestampGenerator().currentTime();
PartitionState state = stateHolder.getState();
try {
synchronized (state) {
HashMap<String, Long> partitions = new HashMap<>(state.partitionKeys);
for (Map.Entry<String, Long> partition : partitions.entrySet()) {
if (partition.getValue() + purgeIdlePeriod < currentTime) {
state.partitionKeys.remove(partition.getKey());
SiddhiAppContext.startPartitionFlow(partition.getKey());
try {
for (QueryRuntime queryRuntime : queryRuntimeList) {
Map<String, StateHolder> elementHolderMap = siddhiAppContext.getSnapshotService().getStateHolderMap(partitionName, queryRuntime.getQueryId());
for (StateHolder stateHolder : elementHolderMap.values()) {
stateHolder.cleanGroupByStates();
}
}
} finally {
SiddhiAppContext.stopPartitionFlow();
}
}
}
}
} finally {
stateHolder.returnState(state);
}
}
}, purgeExecutionInterval, purgeExecutionInterval, TimeUnit.MILLISECONDS);
}
}
use of io.siddhi.core.query.QueryRuntimeImpl in project siddhi by wso2.
the class PartitionStreamReceiver method addStreamJunction.
/**
* create local streamJunctions through which events received by partitionStreamReceiver, are sent to
* queryStreamReceivers
*
* @param queryRuntimeList queryRuntime list of the partition
*/
public void addStreamJunction(List<QueryRuntime> queryRuntimeList) {
StreamJunction streamJunction = streamJunctionMap.get(streamId);
if (streamJunction == null) {
streamJunction = partitionRuntime.getInnerPartitionStreamReceiverStreamJunctionMap().get(streamId);
if (streamJunction == null) {
streamJunction = createStreamJunction();
partitionRuntime.addInnerpartitionStreamReceiverStreamJunction(streamId, streamJunction);
}
streamJunctionMap.put(streamId, streamJunction);
}
for (QueryRuntime queryRuntime : queryRuntimeList) {
StreamRuntime streamRuntime = ((QueryRuntimeImpl) queryRuntime).getStreamRuntime();
for (int i = 0; i < ((QueryRuntimeImpl) queryRuntime).getInputStreamId().size(); i++) {
if ((streamRuntime.getSingleStreamRuntimes().get(i)).getProcessStreamReceiver().getStreamId().equals(streamId)) {
streamJunction.subscribe((streamRuntime.getSingleStreamRuntimes().get(i)).getProcessStreamReceiver());
}
}
}
}
Aggregations