public async Task RestartsRecurringTasks()
        {
            // Note: this is a real-time service! Don't wait for minutes here, otherwise unit tests will take too long ;-)
            var timeService = new TimeService(TimeSpan.FromMinutes(1));
            var schedulingService = new SchedulingService(timeService);

            var scheduledTask1 = new ScheduledTask
            {
                Name = "task 1",
                Start = timeService.CurrentDateTime.AddHours(5)
            };

            schedulingService.AddScheduledTask(scheduledTask1);

            var taskCompletedCounter = 0;
            var scheduledTask2 = new ScheduledTask
            {
                Name = "task 2",
                Start = timeService.CurrentDateTime,
                Action = () =>
                {
                    taskCompletedCounter++;
                    return TaskHelper.Completed;
                },
                Recurring = TimeSpan.FromSeconds(2)
            };

            schedulingService.AddScheduledTask(scheduledTask2);

            var isCanceled = false;
            schedulingService.TaskCanceled += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCanceled = true;
                }
            };

            var isCompleted = false;
            schedulingService.TaskCompleted += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCompleted = true;
                }
            };

            await TaskShim.Delay(TimeSpan.FromSeconds(5));

            schedulingService.Stop();

            Assert.IsTrue(isCompleted);
            Assert.IsFalse(isCanceled);

            Assert.AreEqual(3, taskCompletedCounter);
        }
        public async Task CompletesTasksAfterSpecificPeriod()
        {
            var timeService = new TimeService(TimeSpan.FromSeconds(1));
            var schedulingService = new SchedulingService(timeService);

            var scheduledTask1 = new ScheduledTask
            {
                Name = "task 1",
                Start = timeService.CurrentDateTime.AddHours(5)
            };

            schedulingService.AddScheduledTask(scheduledTask1);

            bool isTaskCompleted = false;
            var scheduledTask2 = new ScheduledTask
            {
                Name = "task 2",
                Start = timeService.CurrentDateTime,
                Action = async () =>
                {
                    await TaskShim.Delay(TimeSpan.FromSeconds(2));
                    isTaskCompleted = true;
                }
            };

            schedulingService.AddScheduledTask(scheduledTask2);

            var isCanceled = false;
            schedulingService.TaskCanceled += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCanceled = true;
                }
            };

            var isCompleted = false;
            schedulingService.TaskCompleted += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCompleted = true;
                }
            };

            await TaskShim.Delay(TimeSpan.FromSeconds(5));

            schedulingService.Stop();

            // Additional wait time to allow canceling etc
            await TaskShim.Delay(TimeSpan.FromSeconds(1));

            Assert.IsTrue(isCompleted);
            Assert.IsTrue(isTaskCompleted);
            Assert.IsFalse(isCanceled);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="engineImportService">engine imports</param>
 /// <param name="variableService">variable names</param>
 /// <param name="configuration">the configuration</param>
 /// <param name="schedulingService">The scheduling service.</param>
 /// <param name="engineURI">The engine URI.</param>
 /// <param name="patternNodeFactory">The pattern node factory.</param>
 /// <param name="namedWindowService">The named window service.</param>
 /// <param name="contextManagementService">The context management service.</param>
 /// <param name="exprDeclaredService">The expr declared service.</param>
 /// <param name="contextDescriptor">optional context description</param>
 /// <param name="tableService">The table service.</param>
 public StatementSpecMapContext(EngineImportService engineImportService, VariableService variableService, ConfigurationInformation configuration, SchedulingService schedulingService, string engineURI, PatternNodeFactory patternNodeFactory, NamedWindowService namedWindowService, ContextManagementService contextManagementService, ExprDeclaredService exprDeclaredService, ContextDescriptor contextDescriptor, TableService tableService)
 {
     PlugInAggregations       = new LazyAllocatedMap <ConfigurationPlugInAggregationMultiFunction, PlugInAggregationMultiFunctionFactory>();
     TableExpressions         = new List <ExprTableAccessNode>(1);
     EngineImportService      = engineImportService;
     VariableService          = variableService;
     Configuration            = configuration;
     VariableNames            = new HashSet <string>();
     SchedulingService        = schedulingService;
     EngineURI                = engineURI;
     PatternNodeFactory       = patternNodeFactory;
     NamedWindowService       = namedWindowService;
     ContextManagementService = contextManagementService;
     ExprDeclaredService      = exprDeclaredService;
     ContextDescriptor        = contextDescriptor;
     TableService             = tableService;
 }
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="schedulingService">The scheduling service.</param>
 /// <param name="variableService">is for variable access</param>
 /// <param name="tableService">The table service.</param>
 /// <param name="isPrioritized">if the engine is running with prioritized execution</param>
 /// <param name="eventProcessingRWLock">The event processing rw lock.</param>
 /// <param name="exceptionHandlingService">The exception handling service.</param>
 /// <param name="metricReportingService">The metric reporting service.</param>
 public NamedWindowDispatchServiceImpl(
     SchedulingService schedulingService,
     VariableService variableService,
     TableService tableService,
     bool isPrioritized,
     IReaderWriterLock eventProcessingRWLock,
     ExceptionHandlingService exceptionHandlingService,
     MetricReportingService metricReportingService)
 {
     _schedulingService        = schedulingService;
     _variableService          = variableService;
     _tableService             = tableService;
     _isPrioritized            = isPrioritized;
     _eventProcessingRwLock    = eventProcessingRWLock;
     _exceptionHandlingService = exceptionHandlingService;
     _metricReportingService   = metricReportingService;
 }
Exemplo n.º 5
0
        void ServiceController_OnChangeServiceState(object sender, EventArgs e)
        {
            switch (((ServiceController)sender).ServiceState)
            {
            case ServiceController.EnumServiceState.Paused:
                SchedulingService.Pause();
                break;

            case ServiceController.EnumServiceState.Stopped:
                SchedulingService.Stop();
                break;

            case ServiceController.EnumServiceState.Started:
                SchedulingService.Resume();
                break;
            }
        }
Exemplo n.º 6
0
 public NamedWindowDispatchServiceImpl(
     SchedulingService schedulingService,
     VariableManagementService variableService,
     TableManagementService tableManagementService,
     bool isPrioritized,
     IReaderWriterLock eventProcessingRWLock,
     ExceptionHandlingService exceptionHandlingService,
     MetricReportingService metricReportingService)
 {
     this.schedulingService = schedulingService;
     this.variableService = variableService;
     this.tableManagementService = tableManagementService;
     this.isPrioritized = isPrioritized;
     this.eventProcessingRWLock = eventProcessingRWLock;
     this.exceptionHandlingService = exceptionHandlingService;
     this.metricReportingService = metricReportingService;
 }
Exemplo n.º 7
0
        public static PatternAgentInstanceContext MakePatternAgentInstanceContext(SchedulingService scheduleService)
        {
            var container = SupportContainer.Instance;

            StatementContext stmtContext;

            if (scheduleService == null)
            {
                stmtContext = SupportStatementContextFactory.MakeContext(container);
            }
            else
            {
                stmtContext = SupportStatementContextFactory.MakeContext(container, scheduleService);
            }
            PatternContext context = new PatternContext(stmtContext, 1, new MatchedEventMapMeta(new String[0], false), false);

            return(new PatternAgentInstanceContext(context, SupportStatementContextFactory.MakeAgentInstanceContext(container), false));
        }
Exemplo n.º 8
0
        public async Task RespectsReschedulingAfterExecutionCompletedIsTrueAsync()
        {
            // Note: this is a real-time service! Don't wait for minutes here, otherwise unit tests will take too long ;-)
            var timeService               = new TimeService(TimeSpan.FromSeconds(1));
            var schedulingService         = new SchedulingService(timeService);
            var hasReceivedCompletedEvent = false;

            var scheduledTask1 = new ScheduledTask
            {
                Name      = "task 1",
                Start     = timeService.CurrentDateTime.AddMinutes(1),
                Recurring = TimeSpan.FromHours(1),
                ScheduleRecurringTaskAfterTaskExecutionHasCompleted = true,
                Action = async() => { await Task.Delay(1000); }
            };

            schedulingService.TaskStarted += (sender, e) =>
            {
                // Task must be *not* here
                var newlyScheduledTask = schedulingService.GetScheduledTasks().FirstOrDefault();

                Assert.IsNull(newlyScheduledTask);
            };

            schedulingService.TaskCompleted += (sender, e) =>
            {
                // Task must be here
                var newlyScheduledTask = schedulingService.GetScheduledTasks().FirstOrDefault();

                Assert.IsNotNull(newlyScheduledTask);

                hasReceivedCompletedEvent = true;
            };

            schedulingService.AddScheduledTask(scheduledTask1);

            schedulingService.Start();

            await Task.Delay(10 * 1000);

            schedulingService.Stop();

            Assert.IsTrue(hasReceivedCompletedEvent);
        }
Exemplo n.º 9
0
        private void RunAssertionLifecycle(EPServiceProvider epService)
        {
            string epl = "@Name('context') create context NineToFive as start (0, 9, *, *, *) end (0, 17, *, *, *)";
            EPServiceProviderSPI     spi               = (EPServiceProviderSPI)epService;
            ContextManagementService ctxMgmtService    = spi.ContextManagementService;
            SchedulingService        schedulingService = spi.SchedulingService;

            Assert.AreEqual(0, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            // create and destroy
            EPStatement stmtContext = epService.EPAdministrator.CreateEPL(epl);

            Assert.AreEqual(1, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            stmtContext.Dispose();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);

            // create context, create statement, destroy statement, destroy context
            stmtContext = epService.EPAdministrator.CreateEPL(epl);
            Assert.AreEqual(1, ctxMgmtService.ContextCount);

            EPStatement stmt = epService.EPAdministrator.CreateEPL("@Name('C') context NineToFive select * from SupportBean");

            Assert.AreEqual(1, schedulingService.ScheduleHandleCount);

            stmt.Dispose();
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            stmtContext.Dispose();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);

            // create same context
            epService.EPAdministrator.CreateEPL(epl);
            epService.EPAdministrator.CreateEPL("@Name('C') context NineToFive select * from SupportBean");
            epService.EPAdministrator.CreateEPL("@Name('D') context NineToFive select * from SupportBean");
            epService.EPAdministrator.DestroyAllStatements();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            epService.EPAdministrator.DestroyAllStatements();
        }
Exemplo n.º 10
0
        /// <summary>Creates the database config service. </summary>
        /// <param name="configSnapshot">is the config snapshot</param>
        /// <param name="schedulingService">is the timer stuff</param>
        /// <param name="schedulingMgmtService">for statement schedule management</param>
        /// <returns>database config svc</returns>
        internal static DatabaseConfigService MakeDatabaseRefService(ConfigurationInformation configSnapshot,
                                                                     SchedulingService schedulingService,
                                                                     SchedulingMgmtService schedulingMgmtService)
        {
            DatabaseConfigService databaseConfigService;

            // Add auto-imports
            try
            {
                ScheduleBucket allStatementsBucket = schedulingMgmtService.AllocateBucket();
                databaseConfigService = new DatabaseConfigServiceImpl(configSnapshot.DatabaseReferences, schedulingService, allStatementsBucket);
            }
            catch (ArgumentException ex)
            {
                throw new ConfigurationException("Error configuring engine: " + ex.Message, ex);
            }

            return(databaseConfigService);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="schedulingService">The scheduling service.</param>
 /// <param name="variableService">is for variable access</param>
 /// <param name="tableService">The table service.</param>
 /// <param name="isPrioritized">if the engine is running with prioritized execution</param>
 /// <param name="eventProcessingRWLock">The event processing rw lock.</param>
 /// <param name="exceptionHandlingService">The exception handling service.</param>
 /// <param name="metricReportingService">The metric reporting service.</param>
 /// <param name="threadLocalManager">The thread local manager.</param>
 public NamedWindowDispatchServiceImpl(
     SchedulingService schedulingService,
     VariableService variableService,
     TableService tableService,
     bool isPrioritized,
     IReaderWriterLock eventProcessingRWLock,
     ExceptionHandlingService exceptionHandlingService,
     MetricReportingService metricReportingService,
     IThreadLocalManager threadLocalManager)
 {
     _threadLocal              = threadLocalManager.Create <DispatchesTL>(() => new DispatchesTL());
     _schedulingService        = schedulingService;
     _variableService          = variableService;
     _tableService             = tableService;
     _isPrioritized            = isPrioritized;
     _eventProcessingRwLock    = eventProcessingRWLock;
     _exceptionHandlingService = exceptionHandlingService;
     _metricReportingService   = metricReportingService;
 }
Exemplo n.º 12
0
        public static void EvaluateSchedule(SchedulingService service)
        {
            ICollection <ScheduleHandle> handles = new LinkedList <ScheduleHandle>();

            service.Evaluate(handles);

            foreach (ScheduleHandle handle in handles)
            {
                if (handle is EPStatementHandleCallback)
                {
                    EPStatementHandleCallback callback = (EPStatementHandleCallback)handle;
                    callback.ScheduleCallback.ScheduledTrigger(null);
                }
                else
                {
                    ScheduleHandleCallback cb = (ScheduleHandleCallback)handle;
                    cb.ScheduledTrigger(null);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="epService">the EPServiceProvider for the engine runtime and services</param>
        /// <param name="usingEngineThread">true if the Adapter should set time by the scheduling service in the engine,false if it should set time externally through the calling thread</param>
        /// <param name="usingExternalTimer">true to use esper's external timer mechanism instead of internal timing</param>
        /// <param name="usingTimeSpanEvents"></param>
        protected AbstractCoordinatedAdapter(EPServiceProvider epService, bool usingEngineThread, bool usingExternalTimer, bool usingTimeSpanEvents)
        {
            UsingEngineThread   = usingEngineThread;
            UsingExternalTimer  = usingExternalTimer;
            UsingTimeSpanEvents = usingTimeSpanEvents;
            Sender = new DirectSender();

            if (epService == null)
            {
                return;
            }
            if (!(epService is EPServiceProviderSPI))
            {
                throw new ArgumentException("Invalid epService provided");
            }

            _epService         = epService;
            Runtime            = epService.EPRuntime;
            _schedulingService = ((EPServiceProviderSPI)epService).SchedulingService;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="runtime">the runtime for the engine runtime</param>
        /// <param name="usingEngineThread">true if the Adapter should set time by the scheduling service in the runtime, false if it should set time externally through the calling thread</param>
        /// <param name="usingExternalTimer">true to use esper's external timer mechanism instead of internal timing</param>
        /// <param name="usingTimeSpanEvents"></param>
        protected AbstractCoordinatedAdapter(EPRuntime runtime, bool usingEngineThread, bool usingExternalTimer, bool usingTimeSpanEvents)
        {
            UsingEngineThread   = usingEngineThread;
            UsingExternalTimer  = usingExternalTimer;
            UsingTimeSpanEvents = usingTimeSpanEvents;
            Sender = new DirectSender();

            if (runtime == null)
            {
                return;
            }
            if (!(runtime is EPRuntimeSPI runtimeSpi))
            {
                throw new ArgumentException("Invalid epService provided");
            }

            _runtime           = runtimeSpi;
            _container         = runtimeSpi.Container;
            _processEvent      = runtime.EventService;
            _schedulingService = runtimeSpi.ServicesContext.SchedulingService;
        }
Exemplo n.º 15
0
        public void TestLifecycle()
        {
            String epl = "@Name('context') create context NineToFive as start (0, 9, *, *, *) end (0, 17, *, *, *)";
            ContextManagementService ctxMgmtService    = _spi.ContextManagementService;
            SchedulingService        schedulingService = _spi.SchedulingService;

            Assert.AreEqual(0, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            // create and destroy
            EPStatement stmtContext = _epService.EPAdministrator.CreateEPL(epl);

            Assert.AreEqual(1, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            stmtContext.Dispose();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);

            // create context, create statement, destroy statement, destroy context
            stmtContext = _epService.EPAdministrator.CreateEPL(epl);
            Assert.AreEqual(1, ctxMgmtService.ContextCount);

            EPStatement stmt = _epService.EPAdministrator.CreateEPL("@Name('C') context NineToFive select * from SupportBean");

            Assert.AreEqual(1, schedulingService.ScheduleHandleCount);

            stmt.Dispose();
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);

            stmtContext.Dispose();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);

            // create same context
            _epService.EPAdministrator.CreateEPL(epl);
            _epService.EPAdministrator.CreateEPL("@Name('C') context NineToFive select * from SupportBean");
            _epService.EPAdministrator.CreateEPL("@Name('D') context NineToFive select * from SupportBean");
            _epService.EPAdministrator.DestroyAllStatements();
            Assert.AreEqual(0, ctxMgmtService.ContextCount);
            Assert.AreEqual(0, schedulingService.ScheduleHandleCount);
        }
Exemplo n.º 16
0
        public static IThreadLocal <EPEventServiceThreadLocalEntry> AllocateThreadLocals(
            bool isPrioritized,
            string runtimeURI,
            EventBeanService eventBeanService,
            ExceptionHandlingService exceptionHandlingService,
            SchedulingService schedulingService)
        {
            return(new FastThreadLocal <EPEventServiceThreadLocalEntry>(
                       () => {
                DualWorkQueue <object> dualWorkQueue = new DualWorkQueue <object>();
                ArrayBackedCollection <FilterHandle> filterHandles = new ArrayBackedCollection <FilterHandle>(100);
                ArrayBackedCollection <ScheduleHandle> scheduleHandles = new ArrayBackedCollection <ScheduleHandle>(100);

                IDictionary <EPStatementAgentInstanceHandle, object> matchesPerStmt;
                IDictionary <EPStatementAgentInstanceHandle, object> schedulesPerStmt;
                if (isPrioritized)
                {
                    matchesPerStmt = new SortedDictionary <EPStatementAgentInstanceHandle, object>(EPStatementAgentInstanceHandleComparer.INSTANCE);
                    schedulesPerStmt = new SortedDictionary <EPStatementAgentInstanceHandle, object>(EPStatementAgentInstanceHandleComparer.INSTANCE);
                }
                else
                {
                    matchesPerStmt = new Dictionary <EPStatementAgentInstanceHandle, object>();
                    schedulesPerStmt = new Dictionary <EPStatementAgentInstanceHandle, object>();
                }

                ExprEvaluatorContext runtimeFilterAndDispatchTimeContext = new EPEventServiceExprEvaluatorContext(
                    runtimeURI,
                    eventBeanService,
                    exceptionHandlingService,
                    schedulingService);
                return new EPEventServiceThreadLocalEntry(
                    dualWorkQueue,
                    filterHandles,
                    scheduleHandles,
                    matchesPerStmt,
                    schedulesPerStmt,
                    runtimeFilterAndDispatchTimeContext);
            }));
        }
Exemplo n.º 17
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="schedulingService">The scheduling service.</param>
 /// <param name="variableService">is for variable access</param>
 /// <param name="tableService">The table service.</param>
 /// <param name="isPrioritized">if the engine is running with prioritized execution</param>
 /// <param name="eventProcessingRWLock">The event processing rw lock.</param>
 /// <param name="exceptionHandlingService">The exception handling service.</param>
 /// <param name="enableQueryPlanLog">if set to <c>true</c> [enable query plan log].</param>
 /// <param name="metricReportingService">The metric reporting service.</param>
 public NamedWindowServiceImpl(
     SchedulingService schedulingService,
     VariableService variableService,
     TableService tableService,
     bool isPrioritized,
     IReaderWriterLock eventProcessingRWLock,
     ExceptionHandlingService exceptionHandlingService,
     bool enableQueryPlanLog,
     MetricReportingService metricReportingService)
 {
     _schedulingService        = schedulingService;
     _processors               = new Dictionary <string, NamedWindowProcessor>();
     _windowStatementLocks     = new Dictionary <string, NamedWindowLockPair>();
     _variableService          = variableService;
     _tableService             = tableService;
     _observers                = new HashSet <NamedWindowLifecycleObserver>();
     _isPrioritized            = isPrioritized;
     _eventProcessingRwLock    = eventProcessingRWLock;
     _exceptionHandlingService = exceptionHandlingService;
     _enableQueryPlanLog       = enableQueryPlanLog;
     _metricReportingService   = metricReportingService;
 }
Exemplo n.º 18
0
        public void SetContext(
            FilterService filterService,
            SchedulingService schedulingService,
            EventServiceSendEventCommon eventServiceSendEventInternal)
        {
            var metricsExecutionContext = new MetricExecutionContext(
                filterService, schedulingService, eventServiceSendEventInternal, stmtMetricRepository);

            // create all runtime and statement executions
            metricExecEngine = new MetricExecEngine(this, runtimeURI, schedule, specification.RuntimeInterval);
            metricExecStmtGroupDefault = new MetricExecStatement(this, schedule, specification.StatementInterval, 0);

            var countGroups = 1;
            foreach (var entry in specification.StatementGroups) {
                var config = entry.Value;
                var metricsExecution = new MetricExecStatement(this, schedule, config.Interval, countGroups);
                statementGroupExecutions.Put(entry.Key, metricsExecution);
                countGroups++;
            }

            // last assign this volatile variable so the time event processing may schedule callbacks
            executionContext = metricsExecutionContext;
        }
Exemplo n.º 19
0
        public Bot(
            ILogger <Bot> logger,
            BotProperties botProperties,
            IServiceProvider serviceProvider,
            DiscordSocketClient client,
            CommandService commandService,
            SchedulingService schedulingService)
        {
            _logger            = logger;
            _botProperties     = botProperties;
            _serviceProvider   = serviceProvider;
            _client            = client;
            _commandService    = commandService;
            _schedulingService = schedulingService;

            _client.Log             += Log;
            _client.MessageReceived += HandleMessage;
            _client.Ready           += ClientReady;
            _client.Disconnected    += HandleDisconnect;

            _commandService.Log             += Log;
            _commandService.CommandExecuted += CommandExecuted;
        }
Exemplo n.º 20
0
        public static AgentInstanceViewFactoryChainContext MakeAgentInstanceViewFactoryContext(SchedulingService stub)
        {
            var agentInstanceContext = MakeAgentInstanceContext(stub);

            return(new AgentInstanceViewFactoryChainContext(agentInstanceContext, false, null, null));
        }
Exemplo n.º 21
0
 public static AgentInstanceContext MakeAgentInstanceContext(SchedulingService stub)
 {
     return(new AgentInstanceContext(MakeContext(stub), null, -1, null, null, null));
 }
Exemplo n.º 22
0
 public ScheduleController(SchedulingService schedulingService, TrackerService trackerService, SteamService steamService)
 {
     _schedulingService = schedulingService;
     _trackerService    = trackerService;
     _steamService      = steamService;
 }
Exemplo n.º 23
0
        public void Validate(
            EngineImportService engineImportService,
            StreamTypeService streamTypeService,
            TimeProvider timeProvider,
            VariableService variableService,
            TableService tableService,
            ScriptingService scriptingService,
            ExprEvaluatorContext exprEvaluatorContext,
            ConfigurationInformation configSnapshot,
            SchedulingService schedulingService,
            string engineURI,
            IDictionary <int, IList <ExprNode> > sqlParameters,
            EventAdapterService eventAdapterService,
            StatementContext statementContext)
        {
            _statementContext = statementContext;

            // validate and visit
            var validationContext        = new ExprValidationContext(streamTypeService, engineImportService, statementContext.StatementExtensionServicesContext, null, timeProvider, variableService, tableService, exprEvaluatorContext, eventAdapterService, statementContext.StatementName, statementContext.StatementId, statementContext.Annotations, null, statementContext.ScriptingService, false, false, true, false, null, false);
            var visitor                  = new ExprNodeIdentifierVisitor(true);
            var validatedInputParameters = new List <ExprNode>();

            foreach (var exprNode in _methodStreamSpec.Expressions)
            {
                var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.METHODINVJOIN, exprNode, validationContext);
                validatedInputParameters.Add(validated);
                validated.Accept(visitor);
            }

            // determine required streams
            _requiredStreams = new SortedSet <int>();
            foreach (var identifier in visitor.ExprProperties)
            {
                _requiredStreams.Add(identifier.First);
            }

            // class-based evaluation
            if (_metadata.MethodProviderClass != null)
            {
                // resolve actual method to use
                var handler = new ProxyExprNodeUtilResolveExceptionHandler {
                    ProcHandle = e => {
                        if (_methodStreamSpec.Expressions.Count == 0)
                        {
                            return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting no parameters in method: " + e.Message, e));
                        }
                        var resultTypes = ExprNodeUtility.GetExprResultTypes(validatedInputParameters);
                        return(new ExprValidationException(
                                   string.Format("Method footprint does not match the number or type of expression parameters, expecting a method where parameters are typed '{0}': {1}", TypeHelper.GetParameterAsString(resultTypes), e.Message), e));
                    }
                };
                var desc = ExprNodeUtility.ResolveMethodAllowWildcardAndStream(
                    _metadata.MethodProviderClass.FullName, _metadata.IsStaticMethod ? null : _metadata.MethodProviderClass,
                    _methodStreamSpec.MethodName, validatedInputParameters, engineImportService, eventAdapterService, statementContext.StatementId,
                    false, null, handler, _methodStreamSpec.MethodName, tableService, statementContext.EngineURI);
                _validatedExprNodes = desc.ChildEvals;

                // Construct polling strategy as a method invocation
                var invocationTarget = _metadata.InvocationTarget;
                var strategy         = _metadata.Strategy;
                var variableReader   = _metadata.VariableReader;
                var variableName     = _metadata.VariableName;
                var methodFastClass  = desc.FastMethod;
                if (_metadata.EventTypeEventBeanArray != null)
                {
                    _pollExecStrategy = new MethodPollingExecStrategyEventBeans(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                }
                else if (_metadata.OptionalMapType != null)
                {
                    if (desc.FastMethod.ReturnType.IsArray)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapCollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyMapPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
                else if (_metadata.OptionalOaType != null)
                {
                    if (desc.FastMethod.ReturnType == typeof(Object[][]))
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOACollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyOAPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
                else
                {
                    if (desc.FastMethod.ReturnType.IsArray)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOArray(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsCollection)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOCollection(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else if (_metadata.IsEnumerator)
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOIterator(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                    else
                    {
                        _pollExecStrategy = new MethodPollingExecStrategyPONOPlain(eventAdapterService, methodFastClass, _eventType, invocationTarget, strategy, variableReader, variableName, variableService);
                    }
                }
            }
            else
            {
                // script-based evaluation
                _pollExecStrategy   = new MethodPollingExecStrategyScript(_metadata.ScriptExpression, _metadata.EventTypeEventBeanArray);
                _validatedExprNodes = ExprNodeUtility.GetEvaluators(validatedInputParameters);
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Creates a new schedule executing once every day.
 /// </summary>
 /// <param name="service">The service to which the schedule should be added.</param>
 /// <returns>A part that allows chained fluent method calls.</returns>
 public static SchedulePart Daily(this SchedulingService service)
 {
     return(service.At("02 4 * * *"));
 }
Exemplo n.º 25
0
 /// <summary>
 /// Creates a new schedule executing once every hour.
 /// </summary>
 /// <param name="service">The service to which the schedule should be added.</param>
 /// <returns>A part that allows chained fluent method calls.</returns>
 public static SchedulePart Hourly(this SchedulingService service)
 {
     return(service.At("01 * * * *"));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Creates a new schedule based on a crontab expression (eg: 0 0 * * *).
        /// Please refer to the project wiki for examples.
        /// </summary>
        /// <param name="service">The service to which the schedule should be added.</param>
        /// <param name="crontab">A crontab expression describing the schedule.</param>
        /// <returns>A part that allows chained fluent method calls.</returns>
        public static SchedulePart At(this SchedulingService service, string crontab)
        {
            var schedule = CrontabSchedule.Parse(crontab);

            return(service.At(schedule.GetNextOccurrence));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Validate the view.
        /// </summary>
        /// <param name="engineImportService">The engine import service.</param>
        /// <param name="streamTypeService">supplies the types of streams against which to validate</param>
        /// <param name="timeProvider">for providing current time</param>
        /// <param name="variableService">for access to variables</param>
        /// <param name="tableService"></param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="exprEvaluatorContext">The expression evaluator context.</param>
        /// <param name="configSnapshot">The config snapshot.</param>
        /// <param name="schedulingService">The scheduling service.</param>
        /// <param name="engineURI">The engine URI.</param>
        /// <param name="sqlParameters">The SQL parameters.</param>
        /// <param name="eventAdapterService">The event adapter service.</param>
        /// <param name="statementContext">The statement context</param>
        /// <throws>  ExprValidationException is thrown to indicate an exception in validating the view </throws>
        public void Validate(EngineImportService engineImportService, StreamTypeService streamTypeService, TimeProvider timeProvider, VariableService variableService, TableService tableService, ScriptingService scriptingService, ExprEvaluatorContext exprEvaluatorContext, ConfigurationInformation configSnapshot, SchedulingService schedulingService, string engineURI, IDictionary <int, IList <ExprNode> > sqlParameters, EventAdapterService eventAdapterService, StatementContext statementContext)
        {
            _statementContext     = statementContext;
            _evaluators           = new ExprEvaluator[_inputParameters.Count];
            _subordinateStreams   = new SortedSet <int>();
            _exprEvaluatorContext = exprEvaluatorContext;

            var count             = 0;
            var validationContext = new ExprValidationContext(
                streamTypeService, engineImportService,
                statementContext.StatementExtensionServicesContext, null,
                timeProvider, variableService, tableService,
                exprEvaluatorContext, eventAdapterService,
                statementContext.StatementName,
                statementContext.StatementId,
                statementContext.Annotations, null,
                scriptingService, false, false, true, false, null, false);

            foreach (var inputParam in _inputParameters)
            {
                var raw = FindSQLExpressionNode(_myStreamNumber, count, sqlParameters);
                if (raw == null)
                {
                    throw new ExprValidationException(
                              "Internal error find expression for historical stream parameter " + count + " stream " +
                              _myStreamNumber);
                }
                var evaluator = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.DATABASEPOLL, raw, validationContext);
                _evaluators[count++] = evaluator.ExprEvaluator;

                var visitor = new ExprNodeIdentifierCollectVisitor();
                visitor.Visit(evaluator);
                foreach (var identNode in visitor.ExprProperties)
                {
                    if (identNode.StreamId == _myStreamNumber)
                    {
                        throw new ExprValidationException("Invalid expression '" + inputParam +
                                                          "' resolves to the historical data itself");
                    }
                    _subordinateStreams.Add(identNode.StreamId);
                }
            }
        }
        public async Task DisablesTimerWhenNoTasksAreScheduled()
        {
            var timeService = new TimeService(TimeSpan.FromMinutes(1));
            var schedulingService = new SchedulingService(timeService);

            schedulingService.Start();
        }
Exemplo n.º 29
0
        public void Validate(
            EngineImportService engineImportService,
            StreamTypeService streamTypeService,
            MethodResolutionService methodResolutionService,
            TimeProvider timeProvider,
            VariableService variableService,
            TableService tableService,
            ScriptingService scriptingService,
            ExprEvaluatorContext exprEvaluatorContext,
            ConfigurationInformation configSnapshot,
            SchedulingService schedulingService,
            string engineURI,
            IDictionary <int, IList <ExprNode> > sqlParameters,
            EventAdapterService eventAdapterService,
            string statementName,
            string statementId,
            Attribute[] annotations)
        {
            // validate and visit
            var validationContext = new ExprValidationContext(
                streamTypeService, methodResolutionService, null, timeProvider, variableService, tableService,
                exprEvaluatorContext, eventAdapterService, statementName, statementId, annotations, null,
                scriptingService, false, false, true, false, null, false);
            var visitor = new ExprNodeIdentifierVisitor(true);
            IList <ExprNode> validatedInputParameters = new List <ExprNode>();

            foreach (var exprNode in _inputParameters)
            {
                var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.METHODINVJOIN, exprNode, validationContext);
                validatedInputParameters.Add(validated);
                validated.Accept(visitor);
            }

            // determine required streams
            _requiredStreams = new SortedSet <int>();
            foreach (var identifier in visitor.ExprProperties)
            {
                _requiredStreams.Add(identifier.First);
            }

            ExprNodeUtilResolveExceptionHandler handler = new ProxyExprNodeUtilResolveExceptionHandler()
            {
                ProcHandle = (e) => {
                    if (_inputParameters.Count == 0)
                    {
                        return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting no parameters in method: " + e.Message));
                    }
                    var resultTypes = ExprNodeUtility.GetExprResultTypes(validatedInputParameters);
                    return(new ExprValidationException("Method footprint does not match the number or type of expression parameters, expecting a method where parameters are typed '" +
                                                       TypeHelper.GetParameterAsString(resultTypes) + "': " + e.Message));
                },
            };

            var desc = ExprNodeUtility.ResolveMethodAllowWildcardAndStream(
                _methodProviderClass.FullName,
                _isStaticMethod ? null : _methodProviderClass,
                _methodStreamSpec.MethodName, validatedInputParameters, methodResolutionService, eventAdapterService, statementId,
                false, null, handler,
                _methodStreamSpec.MethodName, tableService);

            _validatedExprNodes = desc.ChildEvals;
        }
        public async Task RemovesScheduledTasks()
        {
            var timeService = new TimeService(TimeSpan.FromMinutes(1));
            var schedulingService = new SchedulingService(timeService);

            var scheduledTask1 = new ScheduledTask
            {
                Name = "task 1",
                Start = timeService.CurrentDateTime.AddHours(5)
            };

            schedulingService.AddScheduledTask(scheduledTask1);

            var scheduledTask2 = new ScheduledTask
            {
                Name = "task 2",
                Start = timeService.CurrentDateTime,
                Action = async () =>
                {
                    await TaskShim.Delay(TimeSpan.FromMinutes(1));
                }
            };

            schedulingService.AddScheduledTask(scheduledTask2);

            Assert.AreEqual(2, schedulingService.ScheduledTasks.Count);

            schedulingService.RemoveScheduledTask(scheduledTask2);

            Assert.AreEqual(1, schedulingService.ScheduledTasks.Count);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Creates a new schedule executing once every week.
 /// </summary>
 /// <param name="service">The service to which the schedule should be added.</param>
 /// <returns>A part that allows chained fluent method calls.</returns>
 public static SchedulePart Weekly(this SchedulingService service)
 {
     return(service.At("22 4 * * 0"));
 }
Exemplo n.º 32
0
        /// <summary>
        /// Compile the EPL.
        /// </summary>
        /// <param name="eplStatement">expression to compile</param>
        /// <param name="eplStatementForErrorMsg">use this text for the error message</param>
        /// <param name="addPleaseCheck">indicator to add a "please check" wording for stack paraphrases</param>
        /// <param name="statementName">is the name of the statement</param>
        /// <param name="defaultStreamSelector">the configuration for which insert or remove streams (or both) to produce</param>
        /// <param name="engineImportService">The engine import service.</param>
        /// <param name="variableService">The variable service.</param>
        /// <param name="schedulingService">The scheduling service.</param>
        /// <param name="engineURI">The engine URI.</param>
        /// <param name="configSnapshot">The config snapshot.</param>
        /// <param name="patternNodeFactory">The pattern node factory.</param>
        /// <param name="contextManagementService">The context management service.</param>
        /// <param name="exprDeclaredService">The expr declared service.</param>
        /// <param name="tableService">The table service.</param>
        /// <returns>
        /// statement specification
        /// </returns>
        /// <exception cref="EPStatementException">
        /// </exception>
        public static StatementSpecRaw CompileEPL(
            String eplStatement,
            String eplStatementForErrorMsg,
            bool addPleaseCheck,
            String statementName,
            SelectClauseStreamSelectorEnum defaultStreamSelector,
            EngineImportService engineImportService,
            VariableService variableService,
            SchedulingService schedulingService,
            String engineURI,
            ConfigurationInformation configSnapshot,
            PatternNodeFactory patternNodeFactory,
            ContextManagementService contextManagementService,
            ExprDeclaredService exprDeclaredService,
            TableService tableService)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug(".createEPLStmt StatementName=" + statementName + " eplStatement=" + eplStatement);
            }

            var parseResult = ParseHelper.Parse(eplStatement, eplStatementForErrorMsg, addPleaseCheck, EPLParseRule, true);
            var ast         = parseResult.Tree;

            EPLTreeWalkerListener walker = new EPLTreeWalkerListener(
                parseResult.TokenStream,
                engineImportService,
                variableService,
                schedulingService,
                defaultStreamSelector,
                engineURI,
                configSnapshot,
                patternNodeFactory,
                contextManagementService,
                parseResult.Scripts,
                exprDeclaredService,
                tableService);

            try
            {
                ParseHelper.Walk(ast, walker, eplStatement, eplStatementForErrorMsg);
            }
            catch (ASTWalkException ex)
            {
                Log.Error(".createEPL Error validating expression", ex);
                throw new EPStatementException(ex.Message, eplStatementForErrorMsg, ex);
            }
            catch (EPStatementSyntaxException)
            {
                throw;
            }
            catch (Exception ex)
            {
                const string message = "Error in expression";
                Log.Debug(message, ex);
                throw new EPStatementException(GetNullableErrortext(message, ex.Message), eplStatementForErrorMsg, ex);
            }

            if (Log.IsDebugEnabled)
            {
                ASTUtil.DumpAST(ast);
            }

            StatementSpecRaw raw = walker.GetStatementSpec();

            raw.ExpressionNoAnnotations = parseResult.ExpressionWithoutAnnotations;
            return(raw);
        }
Exemplo n.º 33
0
 /// <summary>
 /// Creates a new schedule executing once every month.
 /// </summary>
 /// <param name="service">The service to which the schedule should be added.</param>
 /// <returns>A part that allows chained fluent method calls.</returns>
 public static SchedulePart Monthly(this SchedulingService service)
 {
     return(service.At("42 4 1 * *"));
 }
Exemplo n.º 34
0
 /// <summary>Dispose services. </summary>
 public void Dispose()
 {
     if (ScriptingService != null)
     {
         ScriptingService.Dispose();
     }
     if (ExprDeclaredService != null)
     {
         ExprDeclaredService.Dispose();
     }
     if (DataFlowService != null)
     {
         DataFlowService.Dispose();
     }
     if (VariableService != null)
     {
         VariableService.Dispose();
     }
     if (MetricsReportingService != null)
     {
         MetricsReportingService.Dispose();
     }
     if (ThreadingService != null)
     {
         ThreadingService.Dispose();
     }
     if (StatementLifecycleSvc != null)
     {
         StatementLifecycleSvc.Dispose();
     }
     if (FilterService != null)
     {
         FilterService.Dispose();
     }
     if (SchedulingService != null)
     {
         SchedulingService.Dispose();
     }
     if (SchedulingMgmtService != null)
     {
         SchedulingMgmtService.Dispose();
     }
     if (StreamService != null)
     {
         StreamService.Destroy();
     }
     if (NamedWindowMgmtService != null)
     {
         NamedWindowMgmtService.Dispose();
     }
     if (NamedWindowDispatchService != null)
     {
         NamedWindowDispatchService.Dispose();
     }
     if (EngineLevelExtensionServicesContext != null)
     {
         EngineLevelExtensionServicesContext.Dispose();
     }
     if (StatementIsolationService != null)
     {
         StatementIsolationService.Dispose();
     }
     if (DeploymentStateService != null)
     {
         DeploymentStateService.Dispose();
     }
 }
        public async Task CancelsRunningTasksAboveMaximumDuration()
        {
            var timeService = new TimeService(TimeSpan.FromSeconds(1));
            var schedulingService = new SchedulingService(timeService);

            var scheduledTask1 = new ScheduledTask
            {
                Name = "task 1",
                Start = timeService.CurrentDateTime.AddHours(5)
            };

            schedulingService.AddScheduledTask(scheduledTask1);

            bool isTaskCompleted = false;
            var scheduledTask2 = new ScheduledTask
            {
                Name = "task 2",
                Start = timeService.CurrentDateTime,
                Action = async () =>
                {
                    await TaskShim.Delay(TimeSpan.FromMinutes(1));
                    isTaskCompleted = true;
                },
                MaximumDuration = TimeSpan.FromSeconds(30)
            };

            schedulingService.AddScheduledTask(scheduledTask2);

            var isCanceled = false;
            schedulingService.TaskCanceled += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCanceled = true;
                }
            };

            var isCompleted = false;
            schedulingService.TaskCompleted += (sender, e) =>
            {
                if (ReferenceEquals(e.RunningTask.ScheduledTask, scheduledTask2))
                {
                    isCompleted = true;
                }
            };

            await TaskShim.Delay(TimeSpan.FromSeconds(2));

            Assert.IsFalse(isCompleted);
            Assert.IsFalse(isTaskCompleted);
            Assert.IsTrue(isCanceled);

            schedulingService.Stop();
        }