コード例 #1
0
        public void Sched_Task_TaskWorkItem_CurrentScheduler()
        {
            UnitTestSchedulingContext context             = new UnitTestSchedulingContext();
            OrleansTaskScheduler      scheduler           = TestInternalHelper.InitializeSchedulerForTesting(context);
            ActivationTaskScheduler   activationScheduler = scheduler.GetWorkItemGroup(context).TaskRunner;

            var result0 = new TaskCompletionSource <bool>();
            var result1 = new TaskCompletionSource <bool>();

            Task t1 = null;

            scheduler.QueueWorkItem(new ClosureWorkItem(() =>
            {
                try
                {
                    output.WriteLine("#0 - TaskWorkItem - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                     SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.Equal(activationScheduler, TaskScheduler.Current); //

                    t1 = new Task(() =>
                    {
                        output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                         SynchronizationContext.Current, TaskScheduler.Current);
                        Assert.Equal(activationScheduler, TaskScheduler.Current);  // "TaskScheduler.Current #1"
                        result1.SetResult(true);
                    });
                    t1.Start();

                    result0.SetResult(true);
                }
                catch (Exception exc)
                {
                    result0.SetException(exc);
                }
            }), context);

            result0.Task.Wait(TimeSpan.FromSeconds(1));
            Assert.True(result0.Task.Exception == null, "Task-0 should not throw exception: " + result0.Task.Exception);
            Assert.True(result0.Task.Result, "Task-0 completed");

            Assert.NotNull(t1); // Task-1 started
            result1.Task.Wait(TimeSpan.FromSeconds(1));
            Assert.True(t1.IsCompleted, "Task-1 completed");
            Assert.False(t1.IsFaulted, "Task-1 faulted: " + t1.Exception);
            Assert.True(result1.Task.Result, "Task-1 completed");
        }
コード例 #2
0
        public void Sched_AC_ContinueWith_2_OrleansSched()
        {
            this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(new UnitTestSchedulingContext(), this.loggerFactory);

            var  result1 = new TaskCompletionSource <bool>();
            var  result2 = new TaskCompletionSource <bool>();
            bool failed1 = false;
            bool failed2 = false;

            Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(OneSecond); throw new ArgumentException(); });

            Task task2 = task1.ContinueWith((Task t) =>
            {
                if (!t.IsFaulted)
                {
                    this.output.WriteLine("===> 2");
                }
                else
                {
                    this.output.WriteLine("===> 3");
                    failed1 = true;
                    result1.SetResult(true);
                }
            });
            Task task3 = task1.ContinueWith((Task t) =>
            {
                if (!t.IsFaulted)
                {
                    this.output.WriteLine("===> 4");
                }
                else
                {
                    this.output.WriteLine("===> 5");
                    failed2 = true;
                    result2.SetResult(true);
                }
            });

            task1.Ignore();
            task2.Ignore();
            task3.Ignore();
            Assert.True(result1.Task.Wait(TwoSeconds), "First ContinueWith did not fire.");
            Assert.True(result2.Task.Wait(TwoSeconds), "Second ContinueWith did not fire.");
            Assert.True(failed1);  // "First ContinueWith did not fire error handler."
            Assert.True(failed2);  // "Second ContinueWith did not fire error handler."
        }
コード例 #3
0
        public InsideRuntimeClient(
            ILocalSiloDetails siloDetails,
            TypeMetadataCache typeMetadataCache,
            OrleansTaskScheduler scheduler,
            IServiceProvider serviceProvider,
            MessageFactory messageFactory,
            ITransactionAgent transactionAgent,
            ILoggerFactory loggerFactory,
            IOptions <SiloMessagingOptions> messagingOptions,
            ApplicationRequestsStatisticsGroup appRequestStatistics,
            MessagingTrace messagingTrace,
            GrainReferenceActivator referenceActivator,
            GrainInterfaceTypeResolver interfaceIdResolver,
            GrainInterfaceTypeToGrainTypeResolver interfaceToTypeResolver,
            ImrGrainMethodInvokerProvider invokers)
        {
            this.ServiceProvider       = serviceProvider;
            this.MySilo                = siloDetails.SiloAddress;
            this.disposables           = new List <IDisposable>();
            this.callbacks             = new ConcurrentDictionary <CorrelationId, CallbackData>();
            this.messageFactory        = messageFactory;
            this.transactionAgent      = transactionAgent;
            this.Scheduler             = scheduler;
            this.ConcreteGrainFactory  = new GrainFactory(this, typeMetadataCache, referenceActivator, interfaceIdResolver, interfaceToTypeResolver);
            this.logger                = loggerFactory.CreateLogger <InsideRuntimeClient>();
            this.invokeExceptionLogger = loggerFactory.CreateLogger($"{typeof(Grain).FullName}.InvokeException");
            this.loggerFactory         = loggerFactory;
            this.messagingOptions      = messagingOptions.Value;
            this.appRequestStatistics  = appRequestStatistics;
            this.messagingTrace        = messagingTrace;
            this.invokers              = invokers;

            this.sharedCallbackData = new SharedCallbackData(
                msg => this.UnregisterCallback(msg.Id),
                this.loggerFactory.CreateLogger <CallbackData>(),
                this.messagingOptions,
                this.appRequestStatistics,
                this.messagingOptions.ResponseTimeout);

            this.systemSharedCallbackData = new SharedCallbackData(
                msg => this.UnregisterCallback(msg.Id),
                this.loggerFactory.CreateLogger <CallbackData>(),
                this.messagingOptions,
                this.appRequestStatistics,
                this.messagingOptions.SystemResponseTimeout);
        }
コード例 #4
0
 internal IncomingMessageHandler(
     MessageCenter mc,
     ActivationDirectory ad,
     OrleansTaskScheduler sched,
     Dispatcher dispatcher,
     MessageFactory messageFactory,
     ILogger <IncomingMessageHandler> log,
     MessagingTrace messagingTrace)
 {
     this.messageCenter  = mc;
     this.directory      = ad;
     this.scheduler      = sched;
     this.dispatcher     = dispatcher;
     this.messageFactory = messageFactory;
     this.log            = log;
     this.messagingTrace = messagingTrace;
 }
コード例 #5
0
        internal LocalReminderService(SiloAddress addr, GrainId id, IConsistentRingProvider ring, OrleansTaskScheduler localScheduler, IReminderTable reminderTable)
            : base(id, addr)
        {
            logger = TraceLogger.GetLogger("ReminderService", TraceLogger.LoggerType.Runtime);

            localReminders     = new Dictionary <ReminderIdentity, LocalReminderData>();
            this.ring          = ring;
            scheduler          = localScheduler;
            this.reminderTable = reminderTable;
            status             = ReminderServiceStatus.Booting;
            myRange            = null;
            localTableSequence = 0;
            tardinessStat      = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS);
            IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count);
            ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED);
            startedTask        = new TaskCompletionSource <bool>();
        }
コード例 #6
0
        public InsideRuntimeClient(
            ILocalSiloDetails siloDetails,
            GrainTypeManager typeManager,
            TypeMetadataCache typeMetadataCache,
            OrleansTaskScheduler scheduler,
            IServiceProvider serviceProvider,
            MessageFactory messageFactory,
            ITransactionAgent transactionAgent,
            ILoggerFactory loggerFactory,
            IOptions <SiloMessagingOptions> messagingOptions,
            IGrainCancellationTokenRuntime cancellationTokenRuntime,
            IOptions <SchedulingOptions> schedulerOptions,
            ApplicationRequestsStatisticsGroup appRequestStatistics)
        {
            this.ServiceProvider          = serviceProvider;
            this.MySilo                   = siloDetails.SiloAddress;
            this.disposables              = new List <IDisposable>();
            this.callbacks                = new ConcurrentDictionary <CorrelationId, CallbackData>();
            this.typeManager              = typeManager;
            this.messageFactory           = messageFactory;
            this.transactionAgent         = transactionAgent;
            this.Scheduler                = scheduler;
            this.ConcreteGrainFactory     = new GrainFactory(this, typeMetadataCache);
            this.logger                   = loggerFactory.CreateLogger <InsideRuntimeClient>();
            this.invokeExceptionLogger    = loggerFactory.CreateLogger($"{typeof(Grain).FullName}.InvokeException");
            this.loggerFactory            = loggerFactory;
            this.messagingOptions         = messagingOptions.Value;
            this.cancellationTokenRuntime = cancellationTokenRuntime;
            this.appRequestStatistics     = appRequestStatistics;
            this.schedulingOptions        = schedulerOptions.Value;

            this.sharedCallbackData = new SharedCallbackData(
                msg => this.UnregisterCallback(msg.Id),
                this.loggerFactory.CreateLogger <CallbackData>(),
                this.messagingOptions,
                this.appRequestStatistics,
                this.messagingOptions.ResponseTimeout);

            this.systemSharedCallbackData = new SharedCallbackData(
                msg => this.UnregisterCallback(msg.Id),
                this.loggerFactory.CreateLogger <CallbackData>(),
                this.messagingOptions,
                this.appRequestStatistics,
                this.messagingOptions.SystemResponseTimeout);
        }
コード例 #7
0
        public void Async_Task_Start_ActivationTaskScheduler()
        {
            InitSchedulerLogging();
            UnitTestSchedulingContext cntx = new UnitTestSchedulingContext();
            OrleansTaskScheduler masterScheduler = TestInternalHelper.InitializeSchedulerForTesting(cntx);
            ActivationTaskScheduler activationScheduler = masterScheduler.GetWorkItemGroup(cntx).TaskRunner;

            int expected = 2;
            bool done = false;
            Task<int> t = new Task<int>(() => { done = true; return expected; });
            t.Start(activationScheduler);

            int received = t.Result;
            Assert.IsTrue(t.IsCompleted, "Task should have completed");
            Assert.IsFalse(t.IsFaulted, "Task should not thrown exception: " + t.Exception);
            Assert.IsTrue(done, "Task should be done");
            Assert.AreEqual(expected, received, "Task did not return expected value " + expected);
        }
コード例 #8
0
 public DeploymentLoadPublisher(
     ILocalSiloDetails siloDetails,
     ISiloPerformanceMetrics siloMetrics,
     ISiloStatusOracle siloStatusOracle,
     GlobalConfiguration config,
     IInternalGrainFactory grainFactory,
     OrleansTaskScheduler scheduler)
     : base(Constants.DeploymentLoadPublisherSystemTargetId, siloDetails.SiloAddress)
 {
     this.siloDetails              = siloDetails;
     this.siloMetrics              = siloMetrics;
     this.siloStatusOracle         = siloStatusOracle;
     this.grainFactory             = grainFactory;
     this.scheduler                = scheduler;
     statisticsRefreshTime         = config.DeploymentLoadPublisherRefreshTime;
     periodicStats                 = new ConcurrentDictionary <SiloAddress, SiloRuntimeStatistics>();
     siloStatisticsChangeListeners = new List <ISiloStatisticsChangeListener>();
 }
コード例 #9
0
ファイル: Dispatcher.cs プロジェクト: mixlatte/orleans
        public Dispatcher(
            OrleansTaskScheduler scheduler,
            ISiloMessageCenter transport,
            Catalog catalog,
            ClusterConfiguration config)
        {
            Scheduler              = scheduler;
            this.catalog           = catalog;
            Transport              = transport;
            this.config            = config;
            logger                 = TraceLogger.GetLogger("Dispatcher", TraceLogger.LoggerType.Runtime);
            rejectionInjectionRate = config.Globals.RejectionInjectionRate;
            double messageLossInjectionRate = config.Globals.MessageLossInjectionRate;

            errorInjection     = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d;
            errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate;
            random             = new SafeRandom();
        }
コード例 #10
0
ファイル: GrainTimer.cs プロジェクト: zoeforever/orleans
        private GrainTimer(OrleansTaskScheduler scheduler, IActivationData activationData, ILogger logger, Func <object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name)
        {
            var ctxt = RuntimeContext.CurrentGrainContext;

            scheduler.CheckSchedulingContextValidity(ctxt);
            this.scheduler      = scheduler;
            this.activationData = activationData;
            this.logger         = logger;
            this.Name           = name;
            this.asyncCallback  = asyncCallback;
            timer = new AsyncTaskSafeTimer(logger,
                                           stateObj => TimerTick(stateObj, ctxt),
                                           state);
            this.dueTime     = dueTime;
            timerFrequency   = period;
            previousTickTime = DateTime.UtcNow;
            totalNumTicks    = 0;
        }
コード例 #11
0
 public ClientObserverRegistrar(
     ILocalSiloDetails siloDetails,
     ILocalGrainDirectory grainDirectory,
     OrleansTaskScheduler scheduler,
     IOptions <SiloMessagingOptions> messagingOptions,
     ILoggerFactory loggerFactory,
     IClusterMembershipService clusterMembershipService,
     IAsyncTimerFactory timerFactory)
     : base(Constants.ClientObserverRegistrarId, siloDetails.SiloAddress, loggerFactory)
 {
     this.grainDirectory           = grainDirectory;
     this.myAddress                = siloDetails.SiloAddress;
     this.scheduler                = scheduler;
     this.clusterMembershipService = clusterMembershipService;
     this.messagingOptions         = messagingOptions.Value;
     this.logger       = loggerFactory.CreateLogger <ClientObserverRegistrar>();
     this.refreshTimer = timerFactory.Create(this.messagingOptions.ClientRegistrationRefresh, "ClientObserverRegistrar.ClientRefreshTimer");
 }
コード例 #12
0
        public void Sched_Task_RequestContext_NewTask_ContinueWith()
        {
            UnitTestSchedulingContext rootContext = new UnitTestSchedulingContext();
            OrleansTaskScheduler scheduler = TestInternalHelper.InitializeSchedulerForTesting(rootContext);

            const string key = "K";
            int val = TestConstants.random.Next();
            RequestContext.Set(key, val);

            output.WriteLine("Initial - SynchronizationContext.Current={0} TaskScheduler.Current={1} Thread={2}",
                SynchronizationContext.Current, TaskScheduler.Current, Thread.CurrentThread.ManagedThreadId);

            Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get Initial");

            Task t0 = new Task(() =>
            {
                output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1} Thread={2}",
                    SynchronizationContext.Current, TaskScheduler.Current, Thread.CurrentThread.ManagedThreadId);

                Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #0");

                Task t1 = new Task(() =>
                {
                    output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1} Thread={2}",
                        SynchronizationContext.Current, TaskScheduler.Current, Thread.CurrentThread.ManagedThreadId);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #1");
                });
                Task t2 = t1.ContinueWith(task =>
                {
                    Assert.IsFalse(task.IsFaulted, "Task #1 FAULTED=" + task.Exception);

                    output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1} Thread={2}",
                        SynchronizationContext.Current, TaskScheduler.Current, Thread.CurrentThread.ManagedThreadId);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #2");
                });
                t1.Start(scheduler);
                bool ok = t2.Wait(TimeSpan.FromSeconds(5));
                if (!ok) throw new TimeoutException();
            });
            t0.Start(scheduler);
            bool finished = t0.Wait(TimeSpan.FromSeconds(10));
            if (!finished) throw new TimeoutException();
            Assert.IsFalse(t0.IsFaulted, "Task #0 FAULTED=" + t0.Exception);
        }
コード例 #13
0
 internal IncomingMessageAgent(
     Message.Categories cat,
     IMessageCenter mc,
     ActivationDirectory ad,
     OrleansTaskScheduler sched,
     Dispatcher dispatcher,
     MessageFactory messageFactory,
     ExecutorService executorService,
     ILoggerFactory loggerFactory) :
     base(cat.ToString(), executorService, loggerFactory)
 {
     category            = cat;
     messageCenter       = mc;
     directory           = ad;
     scheduler           = sched;
     this.dispatcher     = dispatcher;
     this.messageFactory = messageFactory;
     OnFault             = FaultBehavior.RestartOnFault;
 }
コード例 #14
0
 internal IncomingMessageAgent(
     Message.Categories cat,
     IMessageCenter mc,
     ActivationDirectory ad,
     OrleansTaskScheduler sched,
     Dispatcher dispatcher,
     MessageFactory messageFactory,
     ILoggerFactory loggerFactory) :
     base(cat.ToString(), loggerFactory)
 {
     category            = cat;
     messageCenter       = mc;
     directory           = ad;
     scheduler           = sched;
     this.dispatcher     = dispatcher;
     this.messageFactory = messageFactory;
     OnFault             = FaultBehavior.RestartOnFault;
     messageCenter.RegisterLocalMessageHandler(cat, ReceiveMessage);
 }
コード例 #15
0
        public async Task Sched_AC_Turn_Execution_Order()
        {
            // Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn?
            // For example, you have a  long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew.
            // You test that no CW/StartNew runs until the main turn is fully done. And run in stress.

            UnitTestSchedulingContext context = new UnitTestSchedulingContext();

            this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.loggerFactory);

            var result1 = new TaskCompletionSource <bool>();
            var result2 = new TaskCompletionSource <bool>();

            this.orleansTaskScheduler.QueueAction(() =>
            {
                this.mainDone  = false;
                this.stageNum1 = this.stageNum2 = 0;

                Task task1 = Task.Factory.StartNew(() => SubProcess1(11));
                Task task2 = task1.ContinueWith((_) => SubProcess1(12));
                Task task3 = task2.ContinueWith((_) => SubProcess1(13));
                Task task4 = task3.ContinueWith((_) => { SubProcess1(14); result1.SetResult(true); });
                task4.Ignore();

                Task task21 = Task.CompletedTask.ContinueWith((_) => SubProcess2(21));
                Task task22 = task21.ContinueWith((_) => { SubProcess2(22); result2.SetResult(true); });
                task22.Ignore();

                Thread.Sleep(TimeSpan.FromSeconds(1));
                this.mainDone = true;
            },
                                                  context);

            try { await result1.Task.WithTimeout(TimeSpan.FromSeconds(3)); }
            catch (TimeoutException) { Assert.True(false, "Timeout-1"); }
            try { await result2.Task.WithTimeout(TimeSpan.FromSeconds(3)); }
            catch (TimeoutException) { Assert.True(false, "Timeout-2"); }

            Assert.NotEqual(0, this.stageNum1); // "Work items did not get executed-1"
            Assert.NotEqual(0, this.stageNum2); // "Work items did not get executed-2"
            Assert.Equal(14, this.stageNum1);   // "Work items executed out of order-1"
            Assert.Equal(22, this.stageNum2);   // "Work items executed out of order-2"
        }
コード例 #16
0
 public ActivationMessageScheduler(
     Catalog catalog,
     Dispatcher dispatcher,
     GrainVersionManifest versionManifest,
     RuntimeMessagingTrace messagingTrace,
     ActivationCollector activationCollector,
     OrleansTaskScheduler scheduler,
     CompatibilityDirectorManager compatibilityDirectorManager,
     IncomingRequestMonitor incomingRequestMonitor)
 {
     _incomingRequestMonitor = incomingRequestMonitor;
     _catalog                      = catalog;
     _versionManifest              = versionManifest;
     _messagingTrace               = messagingTrace;
     _activationCollector          = activationCollector;
     _scheduler                    = scheduler;
     _compatibilityDirectorManager = compatibilityDirectorManager;
     _dispatcher                   = dispatcher;
 }
コード例 #17
0
        public void Async_Task_Start_OrleansTaskScheduler()
        {
            InitSchedulerLogging();
            UnitTestSchedulingContext cntx      = new UnitTestSchedulingContext();
            OrleansTaskScheduler      scheduler = TestInternalHelper.InitializeSchedulerForTesting(cntx);

            int        expected = 2;
            bool       done     = false;
            Task <int> t        = new Task <int>(() => { done = true; return(expected); });

            t.Start(scheduler);

            int received = t.Result;

            Assert.True(t.IsCompleted, "Task should have completed");
            Assert.False(t.IsFaulted, "Task should not thrown exception: " + t.Exception);
            Assert.True(done, "Task should be done");
            Assert.Equal(expected, received);
        }
コード例 #18
0
 internal TypeManager(
     SiloAddress myAddr,
     GrainTypeManager grainTypeManager,
     ISiloStatusOracle oracle,
     OrleansTaskScheduler scheduler,
     TimeSpan refreshClusterMapInterval,
     ImplicitStreamSubscriberTable implicitStreamSubscriberTable,
     IInternalGrainFactory grainFactory,
     CachedVersionSelectorManager versionSelectorManager,
     ILoggerFactory loggerFactory)
     : base(Constants.TypeManagerId, myAddr, loggerFactory)
 {
     if (grainTypeManager == null)
     {
         throw new ArgumentNullException(nameof(grainTypeManager));
     }
     if (oracle == null)
     {
         throw new ArgumentNullException(nameof(oracle));
     }
     if (scheduler == null)
     {
         throw new ArgumentNullException(nameof(scheduler));
     }
     if (implicitStreamSubscriberTable == null)
     {
         throw new ArgumentNullException(nameof(implicitStreamSubscriberTable));
     }
     this.logger           = loggerFactory.CreateLogger <TypeManager>();
     this.grainTypeManager = grainTypeManager;
     this.statusOracle     = oracle;
     this.implicitStreamSubscriberTable = implicitStreamSubscriberTable;
     this.grainFactory           = grainFactory;
     this.versionSelectorManager = versionSelectorManager;
     this.scheduler = scheduler;
     this.refreshClusterMapInterval = refreshClusterMapInterval;
     // We need this so we can place needed local activations
     this.grainTypeManager.SetInterfaceMapsBySilo(new Dictionary <SiloAddress, GrainInterfaceMap>
     {
         { this.Silo, grainTypeManager.GetTypeCodeMap() }
     });
 }
コード例 #19
0
 public SiloStreamProviderRuntime(
     IConsistentRingProvider consistentRingProvider,
     InsideRuntimeClient runtimeClient,
     ImplicitStreamSubscriberTable implicitStreamSubscriberTable,
     OrleansTaskScheduler scheduler,
     ILoggerFactory loggerFactory,
     ILocalSiloDetails siloDetails,
     IGrainContextAccessor grainContextAccessor)
 {
     this.loggerFactory = loggerFactory;
     this.siloDetails = siloDetails;
     this.grainContextAccessor = grainContextAccessor;
     this.consistentRingProvider = consistentRingProvider;
     this.runtimeClient = runtimeClient;
     this.logger = this.loggerFactory.CreateLogger<SiloProviderRuntime>();
     this.grainBasedPubSub = new GrainBasedPubSubRuntime(this.GrainFactory);
     var tmp = new ImplicitStreamPubSub(this.runtimeClient.InternalGrainFactory, implicitStreamSubscriberTable);
     this.implictPubSub = tmp;
     this.combinedGrainBasedAndImplicitPubSub = new StreamPubSubImpl(this.grainBasedPubSub, tmp);
 }
コード例 #20
0
 public DeploymentLoadPublisher(
     ILocalSiloDetails siloDetails,
     ISiloPerformanceMetrics siloMetrics,
     ISiloStatusOracle siloStatusOracle,
     IOptions <SiloStatisticsOptions> statisticsOptions,
     IInternalGrainFactory grainFactory,
     OrleansTaskScheduler scheduler,
     ILoggerFactory loggerFactory)
     : base(Constants.DeploymentLoadPublisherSystemTargetId, siloDetails.SiloAddress, loggerFactory)
 {
     this.logger                   = loggerFactory.CreateLogger <DeploymentLoadPublisher>();
     this.siloDetails              = siloDetails;
     this.siloMetrics              = siloMetrics;
     this.siloStatusOracle         = siloStatusOracle;
     this.grainFactory             = grainFactory;
     this.scheduler                = scheduler;
     statisticsRefreshTime         = statisticsOptions.Value.DeploymentLoadPublisherRefreshTime;
     periodicStats                 = new ConcurrentDictionary <SiloAddress, SiloRuntimeStatistics>();
     siloStatisticsChangeListeners = new List <ISiloStatisticsChangeListener>();
 }
コード例 #21
0
        internal TypeManager(
            SiloAddress myAddr,
            GrainTypeManager grainTypeManager,
            ISiloStatusOracle oracle,
            OrleansTaskScheduler scheduler,
            TimeSpan refreshClusterMapTimeout,
            ImplicitStreamSubscriberTable implicitStreamSubscriberTable,
            IInternalGrainFactory grainFactory,
            CachedVersionSelectorManager versionSelectorManager)
            : base(Constants.TypeManagerId, myAddr)
        {
            if (grainTypeManager == null)
            {
                throw new ArgumentNullException(nameof(grainTypeManager));
            }
            if (oracle == null)
            {
                throw new ArgumentNullException(nameof(oracle));
            }
            if (scheduler == null)
            {
                throw new ArgumentNullException(nameof(scheduler));
            }
            if (implicitStreamSubscriberTable == null)
            {
                throw new ArgumentNullException(nameof(implicitStreamSubscriberTable));
            }

            this.grainTypeManager = grainTypeManager;
            this.statusOracle     = oracle;
            this.implicitStreamSubscriberTable = implicitStreamSubscriberTable;
            this.grainFactory           = grainFactory;
            this.versionSelectorManager = versionSelectorManager;
            this.scheduler = scheduler;
            this.hasToRefreshClusterGrainInterfaceMap = true;
            this.refreshClusterGrainInterfaceMapTimer = new AsyncTaskSafeTimer(
                OnRefreshClusterMapTimer,
                null,
                TimeSpan.Zero,      // Force to do it once right now
                refreshClusterMapTimeout);
        }
コード例 #22
0
        public void Sched_AC_RequestContext_StartNew_ContinueWith()
        {
            UnitTestSchedulingContext rootContext = new UnitTestSchedulingContext();
            OrleansTaskScheduler      scheduler   = TestInternalHelper.InitializeSchedulerForTesting(rootContext);

            const string key = "A";
            int          val = TestConstants.random.Next();

            RequestContext.Set(key, val);

            Console.WriteLine("Initial - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                              SynchronizationContext.Current, TaskScheduler.Current);

            Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get Initial");

            Task t0 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                  SynchronizationContext.Current, TaskScheduler.Current);

                Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #0");

                Task t1 = Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                      SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #1");
                });
                Task t2 = t1.ContinueWith((_) =>
                {
                    Console.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                      SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #2");
                });
                t2.Wait(TimeSpan.FromSeconds(5));
            });

            t0.Wait(TimeSpan.FromSeconds(10));
            Assert.IsTrue(t0.IsCompleted, "Task #0 FAULTED=" + t0.Exception);
        }
コード例 #23
0
        public void Sched_Task_NewTask_ContinueWith_Wrapped_OrleansTaskScheduler()
        {
            UnitTestSchedulingContext rootContext = new UnitTestSchedulingContext();
            OrleansTaskScheduler      scheduler   = TestInternalHelper.InitializeSchedulerForTesting(rootContext);

            Task wrapped = new Task(() =>
            {
                Console.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                  SynchronizationContext.Current, TaskScheduler.Current);

                Task t0 = new Task(() =>
                {
                    Console.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                      SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current #1");
                });
                Task t1 = t0.ContinueWith(task =>
                {
                    Assert.IsFalse(task.IsFaulted, "Task #1 Faulted=" + task.Exception);

                    Console.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                                      SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current #2");
                });
                t0.Start(scheduler);
                bool ok = t1.Wait(TimeSpan.FromSeconds(15));
                if (!ok)
                {
                    throw new TimeoutException();
                }
            });

            wrapped.Start(scheduler);
            bool finished = wrapped.Wait(TimeSpan.FromSeconds(30));

            if (!finished)
            {
                throw new TimeoutException();
            }
        }
コード例 #24
0
        internal Dispatcher(
            OrleansTaskScheduler scheduler,
            ISiloMessageCenter transport,
            Catalog catalog,
            ClusterConfiguration config,
            PlacementDirectorsManager placementDirectorsManager,
            ILocalGrainDirectory localGrainDirectory)
        {
            this.scheduler = scheduler;
            this.catalog   = catalog;
            Transport      = transport;
            this.config    = config;
            this.placementDirectorsManager = placementDirectorsManager;
            this.localGrainDirectory       = localGrainDirectory;
            logger = LogManager.GetLogger("Dispatcher", LoggerType.Runtime);
            rejectionInjectionRate = config.Globals.RejectionInjectionRate;
            double messageLossInjectionRate = config.Globals.MessageLossInjectionRate;

            errorInjection     = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d;
            errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate;
            random             = new SafeRandom();
        }
コード例 #25
0
        public void Sched_Task_StartTask_Wrapped()
        {
            UnitTestSchedulingContext cntx = new UnitTestSchedulingContext();
            OrleansTaskScheduler scheduler = TestInternalHelper.InitializeSchedulerForTesting(cntx);

            ManualResetEvent pause1 = new ManualResetEvent(false);
            ManualResetEvent pause2 = new ManualResetEvent(false);
            Task task1 = new Task(() => { pause1.WaitOne(); output.WriteLine("Task-1"); });
            Task task2 = new Task(() => { pause2.WaitOne(); output.WriteLine("Task-2"); });

            Task wrapper1 = new Task(() =>
            {
                task1.Start(scheduler);
                bool ok = task1.Wait(TimeSpan.FromMilliseconds(100));
                if (!ok) throw new TimeoutException();
            });
            Task wrapper2 = new Task(() =>
            {
                task2.Start(scheduler);
                bool ok = task2.Wait(TimeSpan.FromMilliseconds(100));
                if (!ok) throw new TimeoutException();
            });

            pause1.Set();
            wrapper1.Start(scheduler);
            bool ok1 = wrapper1.Wait(TimeSpan.FromMilliseconds(1000));
            if (!ok1) throw new TimeoutException();

            Assert.IsTrue(task1.IsCompleted, "Task.IsCompleted-1");
            Assert.IsFalse(task1.IsFaulted, "Task.IsFaulted-1");

            wrapper2.Start(scheduler);
            pause2.Set();
            bool finished = wrapper2.Wait(TimeSpan.FromMilliseconds(100));
            if (!finished) throw new TimeoutException();

            Assert.IsTrue(task2.IsCompleted, "Task.IsCompleted-2");
            Assert.IsFalse(task2.IsFaulted, "Task.IsFaulted-2");
        }
コード例 #26
0
 public InsideRuntimeClient(
     ILocalSiloDetails siloDetails,
     ClusterConfiguration config,
     GrainTypeManager typeManager,
     TypeMetadataCache typeMetadataCache,
     OrleansTaskScheduler scheduler,
     IServiceProvider serviceProvider,
     SerializationManager serializationManager,
     MessageFactory messageFactory,
     IEnumerable <IGrainCallFilter> registeredInterceptors,
     Factory <ITransactionAgent> transactionAgent,
     ILoggerFactory loggerFactory,
     IOptions <SiloMessagingOptions> messagingOptions,
     IGrainCancellationTokenRuntime cancellationTokenRuntime)
 {
     this.ServiceProvider      = serviceProvider;
     this.SerializationManager = serializationManager;
     MySilo      = siloDetails.SiloAddress;
     disposables = new List <IDisposable>();
     callbacks   = new ConcurrentDictionary <CorrelationId, CallbackData>();
     Config      = config;
     config.OnConfigChange("Globals/Message", () => ResponseTimeout = Config.Globals.ResponseTimeout);
     this.typeManager          = typeManager;
     this.messageFactory       = messageFactory;
     this.transactionAgent     = new Lazy <ITransactionAgent>(() => transactionAgent());
     this.Scheduler            = scheduler;
     this.ConcreteGrainFactory = new GrainFactory(this, typeMetadataCache);
     tryResendMessage          = msg => this.Dispatcher.TryResendMessage(msg);
     unregisterCallback        = msg => UnRegisterCallback(msg.Id);
     this.siloInterceptors     = new List <IGrainCallFilter>(registeredInterceptors);
     this.logger = loggerFactory.CreateLogger <InsideRuntimeClient>();
     this.invokeExceptionLogger    = loggerFactory.CreateLogger($"{typeof(Grain).FullName}.InvokeException");
     this.loggerFactory            = loggerFactory;
     this.messagingOptions         = messagingOptions.Value;
     this.callbackDataLogger       = new LoggerWrapper <CallbackData>(loggerFactory);
     this.timerLogger              = loggerFactory.CreateLogger <SafeTimer>();
     this.cancellationTokenRuntime = cancellationTokenRuntime;
 }
コード例 #27
0
 public InsideRuntimeClient(
     ILocalSiloDetails siloDetails,
     ClusterConfiguration config,
     GrainTypeManager typeManager,
     TypeMetadataCache typeMetadataCache,
     OrleansTaskScheduler scheduler,
     IServiceProvider serviceProvider,
     SerializationManager serializationManager,
     MessageFactory messageFactory)
 {
     this.ServiceProvider      = serviceProvider;
     this.SerializationManager = serializationManager;
     MySilo      = siloDetails.SiloAddress;
     disposables = new List <IDisposable>();
     callbacks   = new ConcurrentDictionary <CorrelationId, CallbackData>();
     Config      = config;
     config.OnConfigChange("Globals/Message", () => ResponseTimeout = Config.Globals.ResponseTimeout);
     this.typeManager          = typeManager;
     this.messageFactory       = messageFactory;
     this.Scheduler            = scheduler;
     this.ConcreteGrainFactory = new GrainFactory(this, typeMetadataCache);
     tryResendMessage          = msg => this.Dispatcher.TryResendMessage(msg);
     unregisterCallback        = msg => UnRegisterCallback(msg.Id);
 }
コード例 #28
0
        public void Sched_AC_ContinueWith_1_Test()
        {
            UnitTestSchedulingContext context = new UnitTestSchedulingContext();

            this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);

            var result = new TaskCompletionSource <bool>();
            int n      = 0;

            // ReSharper disable AccessToModifiedClosure
            this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
            {
                Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 1b"); });
                Task task2 = task1.ContinueWith((_) => { n = n * 5; this.output.WriteLine("===> 2"); });
                Task task3 = task2.ContinueWith((_) => { n = n / 5; this.output.WriteLine("===> 3"); });
                Task task4 = task3.ContinueWith((_) => { n = n - 2; this.output.WriteLine("===> 4"); result.SetResult(true); });
                task4.Ignore();
            }), context);
            // ReSharper restore AccessToModifiedClosure

            Assert.True(result.Task.Wait(TwoSeconds));
            Assert.True(n != 0, "Work items did not get executed");
            Assert.Equal(1, n);   // "Work items executed out of order"
        }
コード例 #29
0
ファイル: GrainTimer.cs プロジェクト: thakursagar/orleans
 internal static GrainTimer FromTimerCallback(
     OrleansTaskScheduler scheduler,
     TimerCallback callback,
     object state,
     TimeSpan dueTime,
     TimeSpan period,
     string name = null)
 {
     return(new GrainTimer(
                scheduler,
                null,
                ob =>
     {
         if (callback != null)
         {
             callback(ob);
         }
         return TaskDone.Done;
     },
                state,
                dueTime,
                period,
                name));
 }
コード例 #30
0
ファイル: Dispatcher.cs プロジェクト: zeus82/orleans
 internal Dispatcher(
     OrleansTaskScheduler scheduler,
     MessageCenter messageCenter,
     Catalog catalog,
     IOptionsMonitor <SiloMessagingOptions> messagingOptions,
     PlacementService placementService,
     ILocalGrainDirectory localGrainDirectory,
     MessageFactory messageFactory,
     ILoggerFactory loggerFactory,
     ActivationDirectory activationDirectory,
     RuntimeMessagingTrace messagingTrace)
 {
     this.scheduler           = scheduler;
     this.catalog             = catalog;
     this.messageCenter       = messageCenter;
     this.messagingOptions    = messagingOptions.CurrentValue;
     this.placementService    = placementService;
     this.localGrainDirectory = localGrainDirectory;
     this.messageFactory      = messageFactory;
     this.activationDirectory = activationDirectory;
     this.messagingTrace      = messagingTrace;
     this.logger = loggerFactory.CreateLogger <Dispatcher>();
     messageCenter.SetDispatcher(this);
 }