Exemple #1
0
 private void CheckAlreadyAllocated(StatementResourceHolder holder)
 {
     if (holder.NamedWindowProcessorInstance != null)
     {
         throw new IllegalStateException("Failed to allocated processor instance: already allocated and not released");
     }
 }
Exemple #2
0
        public TableStateInstance GetState(int agentInstanceId)
        {
            var createTableResources = _statementContextCreateTable.StatementExtensionServicesContext.StmtResources;

            StatementResourceHolder holder = null;

            if (_statementContextCreateTable.ContextName == null)
            {
                holder = createTableResources.ResourcesUnpartitioned;
            }
            else
            {
                if (createTableResources.ResourcesPartitioned != null)
                {
                    holder = createTableResources.ResourcesPartitioned.Get(agentInstanceId);
                }
            }
            if (holder == null)
            {
                return(null);
            }

            var aggsvc = (AggregationServiceTable)holder.AggregationService;

            return(aggsvc.TableState);
        }
Exemple #3
0
 private void TraverseContextPartitions(
     DeploymentInternal deployment,
     Consumer <StatementResourceHolder> consumer)
 {
     foreach (EPStatement statement in deployment.Statements)
     {
         EPStatementSPI spi = (EPStatementSPI)statement;
         if (spi.StatementContext.ContextName == null)
         {
             StatementResourceHolder holder = spi.StatementContext.StatementCPCacheService.MakeOrGetEntryCanNull(-1, spi.StatementContext);
             consumer.Invoke(holder);
         }
         else
         {
             ContextRuntimeDescriptor contextDesc    = spi.StatementContext.ContextRuntimeDescriptor;
             ContextManager           contextManager = _servicesContext.ContextManagementService.GetContextManager(
                 contextDesc.ContextDeploymentId,
                 contextDesc.ContextName);
             ICollection <int> agentInstanceIds = contextManager.Realization.GetAgentInstanceIds(ContextPartitionSelectorAll.INSTANCE);
             foreach (int agentInstanceId in agentInstanceIds)
             {
                 StatementResourceHolder holder =
                     spi.StatementContext.StatementCPCacheService.MakeOrGetEntryCanNull(agentInstanceId, spi.StatementContext);
                 consumer.Invoke(holder);
             }
         }
     }
 }
Exemple #4
0
        private void AssertResourcesOutputRate(EPStatement stmt, int numExpectedChangeset)
        {
            EPStatementSPI          spi                   = (EPStatementSPI)stmt;
            StatementResourceHolder resources             = spi.StatementContext.StatementExtensionServicesContext.StmtResources.ResourcesUnpartitioned;
            OutputProcessViewBase   outputProcessViewBase = (OutputProcessViewBase)resources.EventStreamViewables[0].Views[0].Views[0];

            Assert.AreEqual(numExpectedChangeset, outputProcessViewBase.NumChangesetRows);
        }
Exemple #5
0
        public NamedWindowProcessorInstance GetProcessorInstanceAllowUnpartitioned(int agentInstanceId)
        {
            if (agentInstanceId == EPStatementStartMethodConst.DEFAULT_AGENT_INSTANCE_ID)
            {
                return(ProcessorInstanceNoContext);
            }
            StatementResourceHolder holder = _statementContextCreateWindow.StatementExtensionServicesContext.StmtResources.GetPartitioned(agentInstanceId);

            return(holder == null ? null : holder.NamedWindowProcessorInstance);
        }
        private void Apply(
            EventBean theEvent,
            EventBean[] eventsPerStream,
            InternalEventRouterEntry entry,
            ExprEvaluatorContext exprEvaluatorContext,
            InstrumentationCommon instrumentation)
        {
            // evaluate
            object[] values;
            if (entry.IsSubselect) {
                StatementResourceHolder holder = entry.StatementContext.StatementCPCacheService.MakeOrGetEntryCanNull(
                    StatementCPCacheService.DEFAULT_AGENT_INSTANCE_ID, entry.StatementContext);
                using (holder.AgentInstanceContext.AgentInstanceLock.AcquireWriteLock())
                {
                    values = ObtainValues(eventsPerStream, entry, exprEvaluatorContext, instrumentation);
                }
            }
            else {
                values = ObtainValues(eventsPerStream, entry, exprEvaluatorContext, instrumentation);
            }

            // apply
            entry.Writer.Write(values, theEvent);
            
            if (entry.SpecialPropWriters.Length > 0) {
                foreach (var special in entry.SpecialPropWriters) {
                    if (special is InternalEventRouterWriterArrayElement array) {
                        var value = array.RhsExpression.Evaluate(eventsPerStream, true, exprEvaluatorContext);
                        if ((value != null) && (array.TypeWidener != null)) {
                            value = array.TypeWidener.Widen(value);
                        }
                        var arrayValue = theEvent.Get(array.PropertyName);
                        if (arrayValue is Array asArrayValue) {
                            var index = array.IndexExpression.Evaluate(eventsPerStream, true, exprEvaluatorContext).AsBoxedInt32();
                            if (index != null) {
                                int len = asArrayValue.Length;
                                if (index < len) {
                                    if (value != null || !asArrayValue.GetType().GetElementType().IsPrimitive) {
                                        asArrayValue.SetValue(value, index.Value);
                                    }
                                } else {
                                    throw new EPException("Array length " + len + " less than index " + index + " for property '" + array.PropertyName + "'");
                                }
                            }
                        }
                    } else if (special is InternalEventRouterWriterCurly) {
                        InternalEventRouterWriterCurly curly = (InternalEventRouterWriterCurly) special;
                        curly.Expression.Evaluate(eventsPerStream, true, exprEvaluatorContext);
                    } else {
                        throw new IllegalStateException("Unrecognized writer " + special);
                    }
                }
            }
        }
Exemple #7
0
 private void AssignAIResourcesForExpressionContextPartitions(
     int agentInstanceId,
     StatementResourceHolder holder)
 {
     AIRegistryUtil.AssignFutures(
         statementAgentInstanceRegistry,
         agentInstanceId,
         holder.AggregationService,
         holder.PriorEvalStrategies,
         holder.PreviousGetterStrategies,
         holder.SubselectStrategies,
         holder.TableAccessStrategies,
         holder.RowRecogPreviousStrategy);
 }
Exemple #8
0
        private void ProcessUnstage(StatementResourceHolder holder)
        {
            AgentInstanceTransferServices xfer = new AgentInstanceTransferServices(
                holder.AgentInstanceContext,
                _servicesContext.FilterService,
                _servicesContext.SchedulingService,
                _servicesContext.InternalEventRouter);

            holder.AgentInstanceStopCallback.Transfer(xfer);
            if (holder.ContextManagerRealization != null)
            {
                holder.ContextManagerRealization.Transfer(xfer);
            }

            holder.AgentInstanceContext.EpStatementAgentInstanceHandle.StatementFilterVersion.StmtFilterVersion = _servicesContext.FilterService.FiltersVersion;
        }
Exemple #9
0
        public NamedWindowProcessorInstance GetProcessorInstance(AgentInstanceContext agentInstanceContext)
        {
            if (_contextName == null)
            {
                StatementResourceHolder holder = _statementResourceService.Unpartitioned;
                return(holder == null ? null : holder.NamedWindowProcessorInstance);
            }

            if (agentInstanceContext.StatementContext.ContextDescriptor == null)
            {
                return(null);
            }

            if (_contextName.Equals(agentInstanceContext.StatementContext.ContextDescriptor.ContextName))
            {
                StatementResourceHolder holder = _statementResourceService.GetPartitioned(agentInstanceContext.AgentInstanceId);
                return(holder == null ? null : holder.NamedWindowProcessorInstance);
            }
            return(null);
        }
Exemple #10
0
 public void RemoveAllInstanceIndexes(IndexMultiKey index)
 {
     if (_contextName == null)
     {
         StatementResourceHolder holder = _statementResourceService.Unpartitioned;
         if (holder != null && holder.NamedWindowProcessorInstance != null)
         {
             holder.NamedWindowProcessorInstance.RemoveIndex(index);
         }
     }
     else
     {
         foreach (var entry in _statementResourceService.ResourcesPartitioned)
         {
             if (entry.Value.NamedWindowProcessorInstance != null)
             {
                 entry.Value.NamedWindowProcessorInstance.RemoveIndex(index);
             }
         }
     }
 }
Exemple #11
0
        public NamedWindowConsumerView AddConsumer(NamedWindowConsumerDesc consumerDesc, bool isSubselect)
        {
            StatementResourceService statementResourceService = _statementContextCreateWindow.StatementExtensionServicesContext.StmtResources;

            // handle same-context consumer
            if (_contextName != null)
            {
                ContextDescriptor contextDescriptor = consumerDesc.AgentInstanceContext.StatementContext.ContextDescriptor;
                if (contextDescriptor != null && _contextName.Equals(contextDescriptor.ContextName))
                {
                    StatementResourceHolder holder = statementResourceService.GetPartitioned(consumerDesc.AgentInstanceContext.AgentInstanceId);
                    return(holder.NamedWindowProcessorInstance.TailViewInstance.AddConsumer(consumerDesc, isSubselect));
                }
                else
                {
                    // consumer is out-of-context
                    return(_tailView.AddConsumer(consumerDesc));     // non-context consumers
                }
            }

            // handle no context associated
            return(statementResourceService.ResourcesUnpartitioned.NamedWindowProcessorInstance.TailViewInstance.AddConsumer(consumerDesc, isSubselect));
        }
Exemple #12
0
        public TableStateInstance GetState(int agentInstanceId)
        {
            StatementResourceHolder holder = null;

            if (ContextName == null)
            {
                holder = _createTableResources.ResourcesUnpartitioned;
            }
            else
            {
                if (_createTableResources.ResourcesPartitioned != null)
                {
                    holder = _createTableResources.ResourcesPartitioned.Get(agentInstanceId);
                }
            }
            if (holder == null)
            {
                return(null);
            }

            var aggsvc = (AggregationServiceTable)holder.AggregationService;

            return(aggsvc.TableState);
        }
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            // validate use of table: may not both read and write
            ValidateTableAccessUse(StatementSpec.IntoTableSpec, StatementSpec.TableNodes);

            var contextName = StatementSpec.OptionalContextName;
            var defaultAgentInstanceContext = GetDefaultAgentInstanceContext(statementContext);
            var selectDesc = EPStatementStartMethodSelectUtil.Prepare(StatementSpec, services, statementContext, isRecoveringResilient, defaultAgentInstanceContext, IsQueryPlanLogging(services), null, null, null);

            statementContext.StatementAgentInstanceFactory = selectDesc.StatementAgentInstanceFactorySelect;

            // allow extension to walk
            statementContext.StatementExtensionServicesContext.PreStartWalk(selectDesc);

            // Determine context
            EPStatementStopMethod stopStatementMethod;
            Viewable           finalViewable;
            AggregationService aggregationService;
            IDictionary <ExprSubselectNode, SubSelectStrategyHolder>       subselectStrategyInstances;
            IDictionary <ExprPriorNode, ExprPriorEvalStrategy>             priorStrategyInstances;
            IDictionary <ExprPreviousNode, ExprPreviousEvalStrategy>       previousStrategyInstances;
            IDictionary <ExprTableAccessNode, ExprTableAccessEvalStrategy> tableAccessStrategyInstances;
            var preloadList = Collections.GetEmptyList <StatementAgentInstancePreload>();
            RegexExprPreviousEvalStrategy matchRecognizePrevEvalStrategy;

            // With context - delegate instantiation to context
            if (StatementSpec.OptionalContextName != null)
            {
                // use statement-wide agent-instance-specific aggregation service
                aggregationService = statementContext.StatementAgentInstanceRegistry.AgentInstanceAggregationService;

                // use statement-wide agent-instance-specific subselects
                var aiRegistryExpr = statementContext.StatementAgentInstanceRegistry.AgentInstanceExprService;

                subselectStrategyInstances = new Dictionary <ExprSubselectNode, SubSelectStrategyHolder>();
                foreach (var entry in selectDesc.SubSelectStrategyCollection.Subqueries)
                {
                    var specificService = aiRegistryExpr.AllocateSubselect(entry.Key);
                    entry.Key.Strategy = specificService;

                    IDictionary <ExprPriorNode, ExprPriorEvalStrategy> subselectPriorStrategies = new Dictionary <ExprPriorNode, ExprPriorEvalStrategy>();
                    foreach (var subselectPrior in entry.Value.PriorNodesList)
                    {
                        var specificSubselectPriorService = aiRegistryExpr.AllocatePrior(subselectPrior);
                        subselectPriorStrategies.Put(subselectPrior, specificSubselectPriorService);
                    }

                    IDictionary <ExprPreviousNode, ExprPreviousEvalStrategy> subselectPreviousStrategies = new Dictionary <ExprPreviousNode, ExprPreviousEvalStrategy>();
                    foreach (var subselectPrevious in entry.Value.PrevNodesList)
                    {
                        var specificSubselectPreviousService = aiRegistryExpr.AllocatePrevious(subselectPrevious);
                        subselectPreviousStrategies.Put(subselectPrevious, specificSubselectPreviousService);
                    }

                    var subselectAggregation = aiRegistryExpr.AllocateSubselectAggregation(entry.Key);
                    var strategyHolder       = new SubSelectStrategyHolder(specificService, subselectAggregation, subselectPriorStrategies, subselectPreviousStrategies, null, null, null);
                    subselectStrategyInstances.Put(entry.Key, strategyHolder);
                }

                // use statement-wide agent-instance-specific "prior"
                priorStrategyInstances = new Dictionary <ExprPriorNode, ExprPriorEvalStrategy>();
                foreach (var priorNode in selectDesc.ViewResourceDelegateUnverified.PriorRequests)
                {
                    var specificService = aiRegistryExpr.AllocatePrior(priorNode);
                    priorStrategyInstances.Put(priorNode, specificService);
                }

                // use statement-wide agent-instance-specific "previous"
                previousStrategyInstances = new Dictionary <ExprPreviousNode, ExprPreviousEvalStrategy>();
                foreach (var previousNode in selectDesc.ViewResourceDelegateUnverified.PreviousRequests)
                {
                    var specificService = aiRegistryExpr.AllocatePrevious(previousNode);
                    previousStrategyInstances.Put(previousNode, specificService);
                }

                // use statement-wide agent-instance-specific match-recognize "previous"
                matchRecognizePrevEvalStrategy = aiRegistryExpr.AllocateMatchRecognizePrevious();

                // use statement-wide agent-instance-specific tables
                tableAccessStrategyInstances = new Dictionary <ExprTableAccessNode, ExprTableAccessEvalStrategy>();
                if (StatementSpec.TableNodes != null)
                {
                    foreach (ExprTableAccessNode tableNode in StatementSpec.TableNodes)
                    {
                        var specificService = aiRegistryExpr.AllocateTableAccess(tableNode);
                        tableAccessStrategyInstances.Put(tableNode, specificService);
                    }
                }

                var mergeView = new ContextMergeView(selectDesc.ResultSetProcessorPrototypeDesc.ResultSetProcessorFactory.ResultEventType);
                finalViewable = mergeView;

                var statement = new ContextManagedStatementSelectDesc(StatementSpec, statementContext, mergeView, selectDesc.StatementAgentInstanceFactorySelect,
                                                                      selectDesc.ResultSetProcessorPrototypeDesc.AggregationServiceFactoryDesc.Expressions,
                                                                      selectDesc.SubSelectStrategyCollection);
                services.ContextManagementService.AddStatement(contextName, statement, isRecoveringResilient);
                var selectStop = selectDesc.StopMethod;
                stopStatementMethod = new ProxyEPStatementStopMethod(() =>
                {
                    services.ContextManagementService.StoppedStatement(
                        contextName,
                        statementContext.StatementName,
                        statementContext.StatementId,
                        statementContext.Expression,
                        statementContext.ExceptionHandlingService);
                    selectStop.Stop();
                });

                selectDesc.DestroyCallbacks.AddCallback(new EPStatementDestroyCallbackContext(services.ContextManagementService, contextName, statementContext.StatementName, statementContext.StatementId));
            }
            // Without context - start here
            else
            {
                var resultOfStart = (StatementAgentInstanceFactorySelectResult)selectDesc.StatementAgentInstanceFactorySelect.NewContext(defaultAgentInstanceContext, isRecoveringResilient);
                finalViewable = resultOfStart.FinalView;
                var startResultStop = services.EpStatementFactory.MakeStopMethod(resultOfStart);
                var selectStop      = selectDesc.StopMethod;
                stopStatementMethod = new ProxyEPStatementStopMethod(() =>
                {
                    StatementAgentInstanceUtil.StopSafe(startResultStop, statementContext);
                    selectStop.Stop();
                });
                aggregationService           = resultOfStart.OptionalAggegationService;
                subselectStrategyInstances   = resultOfStart.SubselectStrategies;
                priorStrategyInstances       = resultOfStart.PriorNodeStrategies;
                previousStrategyInstances    = resultOfStart.PreviousNodeStrategies;
                tableAccessStrategyInstances = resultOfStart.TableAccessEvalStrategies;
                preloadList = resultOfStart.PreloadList;

                matchRecognizePrevEvalStrategy = null;
                if (resultOfStart.TopViews.Length > 0)
                {
                    EventRowRegexNFAViewService matchRecognize = EventRowRegexHelper.RecursiveFindRegexService(resultOfStart.TopViews[0]);
                    if (matchRecognize != null)
                    {
                        matchRecognizePrevEvalStrategy = matchRecognize.PreviousEvaluationStrategy;
                    }
                }

                if (statementContext.StatementExtensionServicesContext != null && statementContext.StatementExtensionServicesContext.StmtResources != null)
                {
                    StatementResourceHolder holder = statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(resultOfStart);
                    statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                    statementContext.StatementExtensionServicesContext.PostProcessStart(resultOfStart, isRecoveringResilient);
                }
            }

            var matchRecognizeNodes = selectDesc.StatementAgentInstanceFactorySelect.ViewResourceDelegate.PerStream[0].MatchRecognizePreviousRequests;

            // assign strategies to expression nodes
            EPStatementStartMethodHelperAssignExpr.AssignExpressionStrategies(
                selectDesc, aggregationService, subselectStrategyInstances, priorStrategyInstances,
                previousStrategyInstances, matchRecognizeNodes, matchRecognizePrevEvalStrategy,
                tableAccessStrategyInstances);

            // execute preload if any
            foreach (var preload in preloadList)
            {
                preload.ExecutePreload();
            }

            // handle association to table
            if (StatementSpec.IntoTableSpec != null)
            {
                services.StatementVariableRefService.AddReferences(statementContext.StatementName, StatementSpec.IntoTableSpec.Name);
            }

            return(new EPStatementStartResult(finalViewable, stopStatementMethod, selectDesc.DestroyCallbacks));
        }
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            CreateTableDesc createDesc = StatementSpec.CreateTableDesc;

            // determine whether already declared
            VariableServiceUtil.CheckAlreadyDeclaredVariable(createDesc.TableName, services.VariableService);
            if (isNewStatement)
            {
                VariableServiceUtil.CheckAlreadyDeclaredTable(createDesc.TableName, services.TableService);
            }
            if (services.EventAdapterService.GetEventTypeByName(createDesc.TableName) != null)
            {
                throw new ExprValidationException("An event type or schema by name '" + createDesc.TableName + "' already exists");
            }

            EPStatementDestroyMethod destroyMethod = new EPStatementDestroyMethod(() =>
            {
                try
                {
                    services.StatementVariableRefService.RemoveReferencesStatement(statementContext.StatementName);
                }
                catch (Exception ex) {
                    log.Error("Error removing table '" + createDesc.TableName + "': " + ex.Message);
                }
            });

            EPStatementStopMethod stopMethod = new EPStatementStopMethod(() => {});

            // Determine event type names
            var internalTypeName = "table_" + createDesc.TableName + "__internal";
            var publicTypeName   = "table_" + createDesc.TableName + "__public";

            TableMetadata metadata;

            try {
                // determine key types
                var keyTypes = GetKeyTypes(createDesc.Columns, services.EngineImportService);

                // check column naming, interpret annotations
                var columnDescs = ValidateExpressions(createDesc.Columns, services, statementContext);

                // analyze and plan the state holders
                var plan = AnalyzePlanAggregations(createDesc.TableName, statementContext, columnDescs, services, internalTypeName, publicTypeName);
                var tableStateRowFactory = plan.StateRowFactory;

                // register new table
                var queryPlanLogging = services.ConfigSnapshot.EngineDefaults.LoggingConfig.IsEnableQueryPlan;
                metadata = services.TableService.AddTable(createDesc.TableName, statementContext.Expression, statementContext.StatementName, keyTypes, plan.TableColumns, tableStateRowFactory, plan.NumberMethodAggregations, statementContext, plan.InternalEventType,
                                                          plan.PublicEventType, plan.EventToPublic, queryPlanLogging);
            }
            catch (ExprValidationException) {
                services.EventAdapterService.RemoveType(internalTypeName);
                services.EventAdapterService.RemoveType(publicTypeName);
                throw;
            }

            // allocate context factory
            var      contextFactory = new StatementAgentInstanceFactoryCreateTable(metadata);
            Viewable outputView;

            if (StatementSpec.OptionalContextName != null)
            {
                var mergeView = new ContextMergeView(metadata.PublicEventType);
                outputView = mergeView;
                var statement = new ContextManagedStatementCreateAggregationVariableDesc(StatementSpec, statementContext, mergeView, contextFactory);
                services.ContextManagementService.AddStatement(StatementSpec.OptionalContextName, statement, isRecoveringResilient);
            }
            else
            {
                var defaultAgentInstanceContext = GetDefaultAgentInstanceContext(statementContext);
                var result = contextFactory.NewContext(defaultAgentInstanceContext, false);
                if (statementContext.StatementExtensionServicesContext != null && statementContext.StatementExtensionServicesContext.StmtResources != null)
                {
                    StatementResourceHolder holder = statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(result);
                    statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                }
                outputView = result.FinalView;
            }

            services.StatementVariableRefService.AddReferences(statementContext.StatementName, createDesc.TableName);

            return(new EPStatementStartResult(outputView, stopMethod, destroyMethod));
        }
 private void ApplyFilterVersion(StatementResourceHolder holder, long filtersVersion)
 {
     holder.AgentInstanceContext.EpStatementAgentInstanceHandle.StatementFilterVersion.StmtFilterVersion = filtersVersion;
 }
Exemple #16
0
        public NamedWindowProcessorInstance GetProcessorInstance(int agentInstanceId)
        {
            StatementResourceHolder holder = _statementContextCreateWindow.StatementExtensionServicesContext.StmtResources.GetPartitioned(agentInstanceId);

            return(holder == null ? null : holder.NamedWindowProcessorInstance);
        }
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            // define stop
            IList <StopCallback> stopCallbacks = new List <StopCallback>();

            // determine context
            var contextName = StatementSpec.OptionalContextName;

            // register agent instance resources for use in HA
            var epStatementAgentInstanceHandle = GetDefaultAgentInstanceHandle(statementContext);

            if (services.SchedulableAgentInstanceDirectory != null)
            {
                services.SchedulableAgentInstanceDirectory.Add(epStatementAgentInstanceHandle);
            }

            // Create view factories and parent view based on a filter specification
            // Since only for non-joins we get the existing stream's lock and try to reuse it's views
            var filterStreamSpec = (FilterStreamSpecCompiled)StatementSpec.StreamSpecs[0];
            InstrumentationAgent instrumentationAgentCreateWindowInsert = null;

            if (InstrumentationHelper.ENABLED)
            {
                var eventTypeName = filterStreamSpec.FilterSpec.FilterForEventType.Name;
                instrumentationAgentCreateWindowInsert = new ProxyInstrumentationAgent()
                {
                    ProcIndicateQ = () => {
                        InstrumentationHelper.Get().QFilterActivationNamedWindowInsert(eventTypeName);
                    },
                    ProcIndicateA = () => {
                        InstrumentationHelper.Get().AFilterActivationNamedWindowInsert();
                    },
                };
            }
            var activator = services.ViewableActivatorFactory.CreateFilterProxy(services, filterStreamSpec.FilterSpec, statementContext.Annotations, false, instrumentationAgentCreateWindowInsert, false);

            // create data window view factories
            var unmaterializedViewChain = services.ViewService.CreateFactories(0, filterStreamSpec.FilterSpec.ResultEventType, filterStreamSpec.ViewSpecs, filterStreamSpec.Options, statementContext);

            // verify data window
            VerifyDataWindowViewFactoryChain(unmaterializedViewChain.FactoryChain);

            // get processor for variant-streams and versioned typed
            var windowName = StatementSpec.CreateWindowDesc.WindowName;
            var optionalRevisionProcessor = statementContext.ValueAddEventService.GetValueAddProcessor(windowName);

            // add named window processor (one per named window for all agent instances)
            var isPrioritized = services.EngineSettingsService.EngineSettings.ExecutionConfig.IsPrioritized;
            var isEnableSubqueryIndexShare = HintEnum.ENABLE_WINDOW_SUBQUERY_INDEXSHARE.GetHint(StatementSpec.Annotations) != null;

            if (!isEnableSubqueryIndexShare && unmaterializedViewChain.FactoryChain[0] is VirtualDWViewFactory)
            {
                isEnableSubqueryIndexShare = true;  // index share is always enabled for virtual data window (otherwise it wouldn't make sense)
            }
            var isBatchingDataWindow     = DetermineBatchingDataWindow(unmaterializedViewChain.FactoryChain);
            var virtualDataWindowFactory = DetermineVirtualDataWindow(unmaterializedViewChain.FactoryChain);
            var optionalUniqueKeyProps   = ViewServiceHelper.GetUniqueCandidateProperties(unmaterializedViewChain.FactoryChain, StatementSpec.Annotations);
            var processor = services.NamedWindowService.AddProcessor(windowName, contextName, filterStreamSpec.FilterSpec.ResultEventType, statementContext.StatementResultService, optionalRevisionProcessor, statementContext.Expression, statementContext.StatementName, isPrioritized, isEnableSubqueryIndexShare, isBatchingDataWindow, virtualDataWindowFactory != null, statementContext.EpStatementHandle.MetricsHandle, optionalUniqueKeyProps,
                                                                     StatementSpec.CreateWindowDesc.AsEventTypeName,
                                                                     statementContext.StatementExtensionServicesContext.StmtResources);

            Viewable finalViewable;
            EPStatementStopMethod    stopStatementMethod;
            EPStatementDestroyMethod destroyStatementMethod;

            try {
                // add stop callback
                stopCallbacks.Add(() =>
                {
                    services.NamedWindowService.RemoveProcessor(windowName);
                    if (virtualDataWindowFactory != null)
                    {
                        virtualDataWindowFactory.DestroyNamedWindow();
                    }
                });

                // Add a wildcard to the select clause as subscribers received the window contents
                StatementSpec.SelectClauseSpec.SetSelectExprList(new SelectClauseElementWildcard());
                StatementSpec.SelectStreamDirEnum = SelectClauseStreamSelectorEnum.RSTREAM_ISTREAM_BOTH;

                // obtain result set processor factory
                StreamTypeService typeService   = new StreamTypeServiceImpl(new EventType[] { processor.NamedWindowType }, new String[] { windowName }, new bool[] { true }, services.EngineURI, false);
                var resultSetProcessorPrototype = ResultSetProcessorFactoryFactory.GetProcessorPrototype(
                    StatementSpec, statementContext, typeService, null, new bool[0], true, null, null, services.ConfigSnapshot);

                // obtain factory for output limiting
                var outputViewFactory = OutputProcessViewFactoryFactory.Make(StatementSpec, services.InternalEventRouter, statementContext, resultSetProcessorPrototype.ResultSetProcessorFactory.ResultEventType, null, services.TableService, resultSetProcessorPrototype.ResultSetProcessorFactory.ResultSetProcessorType);

                // create context factory
                // Factory for statement-context instances
                var contextFactory = new StatementAgentInstanceFactoryCreateWindow(statementContext, StatementSpec, services, activator, unmaterializedViewChain, resultSetProcessorPrototype, outputViewFactory, isRecoveringStatement);

                // With context - delegate instantiation to context
                EPStatementStopMethod stopMethod = new EPStatementStopMethodImpl(statementContext, stopCallbacks).Stop;
                if (StatementSpec.OptionalContextName != null)
                {
                    var mergeView = new ContextMergeView(processor.NamedWindowType);
                    finalViewable = mergeView;

                    var statement = new ContextManagedStatementCreateWindowDesc(StatementSpec, statementContext, mergeView, contextFactory);
                    services.ContextManagementService.AddStatement(contextName, statement, isRecoveringResilient);
                    stopStatementMethod = () =>
                    {
                        services.ContextManagementService.StoppedStatement(contextName, statementContext.StatementName, statementContext.StatementId);
                        stopMethod.Invoke();
                    };

                    destroyStatementMethod = () =>
                    {
                        services.ContextManagementService.DestroyedStatement(contextName, statementContext.StatementName, statementContext.StatementId);
                    };
                }
                // Without context - start here
                else
                {
                    var agentInstanceContext = GetDefaultAgentInstanceContext(statementContext);
                    StatementAgentInstanceFactoryCreateWindowResult resultOfStart;
                    try {
                        resultOfStart = (StatementAgentInstanceFactoryCreateWindowResult)contextFactory.NewContext(agentInstanceContext, isRecoveringResilient);
                    }
                    catch (Exception ex) {
                        services.NamedWindowService.RemoveProcessor(windowName);
                        throw;
                    }
                    finalViewable       = resultOfStart.FinalView;
                    stopStatementMethod = () =>
                    {
                        resultOfStart.StopCallback.Invoke();
                        stopMethod.Invoke();
                    };
                    destroyStatementMethod = null;

                    if (statementContext.StatementExtensionServicesContext != null && statementContext.StatementExtensionServicesContext.StmtResources != null)
                    {
                        StatementResourceHolder holder = statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(resultOfStart);
                        statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                        statementContext.StatementExtensionServicesContext.PostProcessStart(resultOfStart, isRecoveringResilient);
                    }
                }
            }
            catch (ExprValidationException) {
                services.NamedWindowService.RemoveProcessor(windowName);
                throw;
            }
            catch (Exception) {
                services.NamedWindowService.RemoveProcessor(windowName);
                throw;
            }

            return(new EPStatementStartResult(finalViewable, stopStatementMethod, destroyStatementMethod));
        }
Exemple #18
0
        public NamedWindowProcessorInstance GetProcessorInstance(int agentInstanceId)
        {
            StatementResourceHolder holder = _statementResourceService.GetPartitioned(agentInstanceId);

            return(holder == null ? null : holder.NamedWindowProcessorInstance);
        }