예제 #1
0
 internal SchedulingContext(SystemTarget systemTarget, bool lowPrioritySystemTarget)
 {
     SystemTarget = systemTarget;
     ContextType  = SchedulingContextType.SystemTarget;
     isLowPrioritySystemTarget = lowPrioritySystemTarget;
     IsReactiveComputation     = false;
 }
예제 #2
0
        public Merger(SystemTarget target, bool isTestMode)
        {
            _target = target;

            _rootFolderPath = !isTestMode
                                                  ? FilePaths.GenerateXamlSearchFolderPath()
                                                  : FilePaths.GetExecutingAssemblyFilePath();
        }
예제 #3
0
		public Merger(SystemTarget target, bool isTestMode)
		{
			_target = target;

			_rootFolderPath = !isTestMode
				                  ? FilePaths.GenerateXamlSearchFolderPath()
				                  : FilePaths.GetExecutingAssemblyFilePath();
		}
예제 #4
0
		public static string GenerateGenericFilePath(SystemTarget target)
		{
			return Path.Combine(
				BaseFolderPath,
				Constants.ControlFolder + "." + SystemTargets.GetSystemTargetPath(target).Replace(" ", ""),
				Constants.ThemesFolder,
				Constants.GenericThemeXaml);
		}
예제 #5
0
 public static string GenerateGenericFilePath(SystemTarget target)
 {
     return(Path.Combine(
                BaseFolderPath,
                Constants.ControlFolder + "." + SystemTargets.GetSystemTargetPath(target).Replace(" ", ""),
                Constants.ThemesFolder,
                Constants.GenericThemeXaml));
 }
		public static string GetSystemTargetPath(SystemTarget target)
		{
			switch (target)
			{
				case SystemTarget.WindowsPhone7:
					return Constants.WindowsPhone7;
				case SystemTarget.WindowsPhone8:
					return Constants.WindowsPhone8;
				case SystemTarget.WindowsStore:
					return Constants.WindowsStore;
				default:
					return null;
			}
		}
예제 #7
0
        public string DetailedStatus()
        {
            switch (ContextType)
            {
            case SchedulingContextType.Activation:
                return(Activation.ToDetailedString(true));

            case SchedulingContextType.SystemTarget:
                return(SystemTarget.ToDetailedString());

            case SchedulingContextType.SystemThread:
                return(String.Format("DispatcherTarget{0}", DispatcherTarget));

            default:
                return(ContextType.ToString());
            }
        }
예제 #8
0
        public static string GetSystemTargetPath(SystemTarget target)
        {
            switch (target)
            {
            case SystemTarget.WindowsPhone7:
                return(Constants.WindowsPhone7);

            case SystemTarget.WindowsPhone8:
                return(Constants.WindowsPhone8);

            case SystemTarget.WindowsStore:
                return(Constants.WindowsStore);

            default:
                return(null);
            }
        }
예제 #9
0
        public override string ToString()
        {
            switch (ContextType)
            {
            case SchedulingContextType.Activation:
                return(Activation.ToString());

            case SchedulingContextType.SystemTarget:
                return(SystemTarget.ToString());

            case SchedulingContextType.SystemThread:
                return(String.Format("DispatcherTarget{0}", DispatcherTarget));

            default:
                return(ContextType.ToString());
            }
        }
예제 #10
0
        private static string GetFileTypeByTarget(SystemTarget target)
        {
            switch (target)
            {
            case SystemTarget.WindowsPhone:
                return(Constants.WindowsPhoneEndFileName);

            case SystemTarget.WindowsPhone7:
                return(Constants.WindowsPhone7EndFileName);

            case SystemTarget.WindowsPhone8:
                return(Constants.WindowsPhone8EndFileName);

            case SystemTarget.WindowsStore:
                return(Constants.WindowsStoreEndFileName);
            }

            throw new ArgumentOutOfRangeException("target", target, "cannot find target");
        }
예제 #11
0
        private bool AreSame(object obj)
        {
            var other = obj as SchedulingContext;

            switch (ContextType)
            {
            case SchedulingContextType.Activation:
                return(other != null && Activation.Equals(other.Activation));

            case SchedulingContextType.SystemTarget:
                return(other != null && SystemTarget.Equals(other.SystemTarget));

            case SchedulingContextType.SystemThread:
                return(other != null && DispatcherTarget.Equals(other.DispatcherTarget));

            default:
                return(false);
            }
        }
예제 #12
0
 internal SchedulingContext(SystemTarget systemTarget, bool lowPrioritySystemTarget)
 {
     SystemTarget = systemTarget;
     ContextType  = SchedulingContextType.SystemTarget;
     isLowPrioritySystemTarget = lowPrioritySystemTarget;
 }
예제 #13
0
 public ResponseWorkItem(SystemTarget t, Message m)
 {
     target   = t;
     response = m;
 }
예제 #14
0
 public ResponseWorkItem(SystemTarget t, Message m)
 {
     target = t;
     response = m;
 }
예제 #15
0
        public static IServiceCollection AddLegacyClusterConfigurationSupport(this IServiceCollection services, ClusterConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (services.Any(service => service.ServiceType == typeof(ClusterConfiguration)))
            {
                throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice");
            }

            // these will eventually be removed once our code doesn't depend on the old ClientConfiguration
            services.AddSingleton(configuration);
            services.TryAddSingleton <LegacyConfigurationWrapper>();
            services.TryAddSingleton(sp => sp.GetRequiredService <LegacyConfigurationWrapper>().ClusterConfig.Globals);
            services.TryAddTransient(sp => sp.GetRequiredService <LegacyConfigurationWrapper>().NodeConfig);
            services.TryAddSingleton <Factory <NodeConfiguration> >(
                sp =>
            {
                var initializationParams = sp.GetRequiredService <LegacyConfigurationWrapper>();
                return(() => initializationParams.NodeConfig);
            });

            services.Configure <SiloOptions>(options =>
            {
                if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId))
                {
                    options.ClusterId = configuration.Globals.ClusterId;
                }

                if (options.ServiceId == Guid.Empty)
                {
                    options.ServiceId = configuration.Globals.ServiceId;
                }
            });

            services.Configure <MultiClusterOptions>(options =>
            {
                var globals = configuration.Globals;
                if (globals.HasMultiClusterNetwork)
                {
                    options.HasMultiClusterNetwork            = true;
                    options.BackgroundGossipInterval          = globals.BackgroundGossipInterval;
                    options.DefaultMultiCluster               = globals.DefaultMultiCluster?.ToList();
                    options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries;
                    options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval;
                    options.MaxMultiClusterGateways           = globals.MaxMultiClusterGateways;
                    options.UseGlobalSingleInstanceByDefault  = globals.UseGlobalSingleInstanceByDefault;
                }
            });

            services.TryAddFromExisting <IMessagingConfiguration, GlobalConfiguration>();

            services.AddOptions <StatisticsOptions>()
            .Configure <NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options));

            // Translate legacy configuration to new Options
            services.Configure <SiloMessagingOptions>(options =>
            {
                LegacyConfigurationExtensions.CopyCommonMessagingOptions(configuration.Globals, options);

                options.SiloSenderQueues    = configuration.Globals.SiloSenderQueues;
                options.GatewaySenderQueues = configuration.Globals.GatewaySenderQueues;
                options.MaxForwardCount     = configuration.Globals.MaxForwardCount;
                options.ClientDropTimeout   = configuration.Globals.ClientDropTimeout;
            });

            services.Configure <NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options));

            services.AddOptions <EndpointOptions>()
            .Configure <IOptions <SiloOptions> >((options, siloOptions) =>
            {
                var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
                if (options.IPAddress == null && string.IsNullOrWhiteSpace(options.HostNameOrIPAddress))
                {
                    options.IPAddress = nodeConfig.Endpoint.Address;
                    options.Port      = nodeConfig.Endpoint.Port;
                }
                if (options.ProxyPort == 0 && nodeConfig.ProxyGatewayEndpoint != null)
                {
                    options.ProxyPort = nodeConfig.ProxyGatewayEndpoint.Port;
                }
            });

            services.Configure <SerializationProviderOptions>(options =>
            {
                options.SerializationProviders        = configuration.Globals.SerializationProviders;
                options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider;
            });

            services.AddOptions <GrainClassOptions>().Configure <IOptions <SiloOptions> >((options, siloOptions) =>
            {
                var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
                options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes);
            });

            LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, services);

            services.AddOptions <SchedulingOptions>().Configure <GlobalConfiguration>((options, config) =>
            {
                options.AllowCallChainReentrancy = config.AllowCallChainReentrancy;
                options.PerformDeadlockDetection = config.PerformDeadlockDetection;
            });

            services.TryAddSingleton <LegacyProviderConfigurator.ScheduleTask>(sp =>
            {
                OrleansTaskScheduler scheduler    = sp.GetRequiredService <OrleansTaskScheduler>();
                SystemTarget fallbackSystemTarget = sp.GetRequiredService <FallbackSystemTarget>();
                return((taskFunc) => scheduler.QueueTask(taskFunc, fallbackSystemTarget.SchedulingContext));
            });
            LegacyProviderConfigurator <ISiloLifecycle> .ConfigureServices(configuration.Globals.ProviderConfigurations, services, SiloDefaultProviderInitStage, SiloDefaultProviderStartStage);

            return(services);
        }
예제 #16
0
 internal SchedulingContext(SystemTarget systemTarget, bool lowPrioritySystemTarget)
 {
     SystemTarget = systemTarget;
     ContextType = SchedulingContextType.SystemTarget;
     isLowPrioritySystemTarget = lowPrioritySystemTarget;
 }
예제 #17
0
		public static string GenerateGenericFilePath(SystemTarget target)
		{
			return Path.Combine(BaseFilePath, SystemTargets.GetSystemTargetPath(target), Constants.GenericThemeFile);
		}
예제 #18
0
        public void ReceiveMessage(Message msg)
        {
            this.messagingTrace.OnIncomingMessageAgentReceiveMessage(msg);

            ISchedulingContext context;

            // Find the activation it targets; first check for a system activation, then an app activation
            if (msg.TargetGrain.IsSystemTarget)
            {
                SystemTarget target = this.directory.FindSystemTarget(msg.TargetActivation);
                if (target == null)
                {
                    MessagingStatisticsGroup.OnRejectedMessage(msg);
                    Message response = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable,
                                                                                   string.Format("SystemTarget {0} not active on this silo. Msg={1}", msg.TargetGrain, msg));
                    this.messageCenter.SendMessage(response);
                    this.log.Warn(ErrorCode.MessagingMessageFromUnknownActivation, "Received a message {0} for an unknown SystemTarget: {1}", msg, msg.TargetAddress);
                    return;
                }
                context = target.SchedulingContext;
                switch (msg.Direction)
                {
                case Message.Directions.Request:
                    this.messagingTrace.OnEnqueueMessageOnActivation(msg, context);
                    this.scheduler.QueueWorkItem(new RequestWorkItem(target, msg), context);
                    break;

                case Message.Directions.Response:
                    this.messagingTrace.OnEnqueueMessageOnActivation(msg, context);
                    this.scheduler.QueueWorkItem(new ResponseWorkItem(target, msg), context);
                    break;

                default:
                    this.log.Error(ErrorCode.Runtime_Error_100097, "Invalid message: " + msg);
                    break;
                }
            }
            else
            {
                // Run this code on the target activation's context, if it already exists
                ActivationData targetActivation = this.directory.FindTarget(msg.TargetActivation);
                if (targetActivation != null)
                {
                    lock (targetActivation)
                    {
                        var target = targetActivation; // to avoid a warning about nulling targetActivation under a lock on it
                        if (target.State == ActivationState.Valid)
                        {
                            // Response messages are not subject to overload checks.
                            if (msg.Direction != Message.Directions.Response)
                            {
                                var overloadException = target.CheckOverloaded(this.log);
                                if (overloadException != null)
                                {
                                    // Send rejection as soon as we can, to avoid creating additional work for runtime
                                    this.dispatcher.RejectMessage(msg, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + target);
                                    return;
                                }
                            }

                            // Run ReceiveMessage in context of target activation
                            context = target.SchedulingContext;
                        }
                        else
                        {
                            // Can't use this activation - will queue for another activation
                            target  = null;
                            context = null;
                        }

                        EnqueueReceiveMessage(msg, target, context);
                    }
                }
                else
                {
                    // No usable target activation currently, so run ReceiveMessage in system context
                    EnqueueReceiveMessage(msg, null, null);
                }
            }

            void EnqueueReceiveMessage(Message msg, ActivationData targetActivation, ISchedulingContext context)
            {
                this.messagingTrace.OnEnqueueMessageOnActivation(msg, context);
                targetActivation?.IncrementEnqueuedOnDispatcherCount();
                scheduler.QueueWorkItem(new ClosureWorkItem(() =>
                {
                    try
                    {
                        dispatcher.ReceiveMessage(msg);
                    }
                    finally
                    {
                        targetActivation?.DecrementEnqueuedOnDispatcherCount();
                    }
                },
                                                            "Dispatcher.ReceiveMessage"), context);
            }
        }
예제 #19
0
 public RequestWorkItem(SystemTarget t, Message m)
 {
     target = t;
     request = m;
 }
예제 #20
0
		private static string GetFileTypeByTarget(SystemTarget target)
		{
			switch (target)
			{
				case SystemTarget.WindowsPhone:
					return Constants.WindowsPhoneEndFileName;
				case SystemTarget.WindowsPhone7:
					return Constants.WindowsPhone7EndFileName;
				case SystemTarget.WindowsPhone8:
					return Constants.WindowsPhone8EndFileName;
				case SystemTarget.WindowsStore:
					return Constants.WindowsStoreEndFileName;
			}

			throw new ArgumentOutOfRangeException("target", target, "cannot find target");
		}
예제 #21
0
        private void ReceiveMessage(Message msg)
        {
            MessagingProcessingStatisticsGroup.OnImaMessageReceived(msg);

            ISchedulingContext context;

            // Find the activation it targets; first check for a system activation, then an app activation
            if (msg.TargetGrain.IsSystemTarget)
            {
                SystemTarget target = directory.FindSystemTarget(msg.TargetActivation);
                if (target == null)
                {
                    MessagingStatisticsGroup.OnRejectedMessage(msg);
                    Message response = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable,
                                                                                   String.Format("SystemTarget {0} not active on this silo. Msg={1}", msg.TargetGrain, msg));
                    messageCenter.SendMessage(response);
                    Log.Warn(ErrorCode.MessagingMessageFromUnknownActivation, "Received a message {0} for an unknown SystemTarget: {1}", msg, msg.TargetAddress);
                    return;
                }
                context = target.SchedulingContext;
                switch (msg.Direction)
                {
                case Message.Directions.Request:
                    MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context);
                    scheduler.QueueWorkItem(new RequestWorkItem(target, msg), context);
                    break;

                case Message.Directions.Response:
                    MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context);
                    scheduler.QueueWorkItem(new ResponseWorkItem(target, msg), context);
                    break;

                default:
                    Log.Error(ErrorCode.Runtime_Error_100097, "Invalid message: " + msg);
                    break;
                }
            }
            else
            {
                // Run this code on the target activation's context, if it already exists
                ActivationData targetActivation = directory.FindTarget(msg.TargetActivation);
                if (targetActivation != null)
                {
                    lock (targetActivation)
                    {
                        var target = targetActivation; // to avoid a warning about nulling targetActivation under a lock on it
                        if (target.State == ActivationState.Valid)
                        {
                            var overloadException = target.CheckOverloaded(Log);
                            if (overloadException != null)
                            {
                                // Send rejection as soon as we can, to avoid creating additional work for runtime
                                dispatcher.RejectMessage(msg, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + target);
                                return;
                            }

                            // Run ReceiveMessage in context of target activation
                            context = new SchedulingContext(target);
                        }
                        else
                        {
                            // Can't use this activation - will queue for another activation
                            target  = null;
                            context = null;
                        }

                        EnqueueReceiveMessage(msg, target, context);
                    }
                }
                else
                {
                    // No usable target activation currently, so run ReceiveMessage in system context
                    EnqueueReceiveMessage(msg, null, null);
                }
            }
        }
예제 #22
0
 public RequestWorkItem(SystemTarget t, Message m)
 {
     target  = t;
     request = m;
 }
        public static IServiceCollection AddLegacyClusterConfigurationSupport(this IServiceCollection services, ClusterConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (services.TryGetClusterConfiguration() != null)
            {
                throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice");
            }

            // these will eventually be removed once our code doesn't depend on the old ClientConfiguration
            services.AddSingleton(configuration);
            services.TryAddSingleton <LegacyConfigurationWrapper>();
            services.TryAddSingleton(sp => sp.GetRequiredService <LegacyConfigurationWrapper>().ClusterConfig.Globals);
            services.TryAddTransient(sp => sp.GetRequiredService <LegacyConfigurationWrapper>().NodeConfig);
            services.TryAddSingleton <Factory <NodeConfiguration> >(
                sp =>
            {
                var initializationParams = sp.GetRequiredService <LegacyConfigurationWrapper>();
                return(() => initializationParams.NodeConfig);
            });

            services.Configure <SiloOptions>(options =>
            {
                if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId))
                {
                    options.ClusterId = configuration.Globals.ClusterId;
                }

                if (options.ServiceId == Guid.Empty)
                {
                    options.ServiceId = configuration.Globals.ServiceId;
                }
                options.FastKillOnCancelKeyPress = configuration.Globals.FastKillOnCancelKeyPress;
            });

            services.Configure <MultiClusterOptions>(options =>
            {
                var globals = configuration.Globals;
                if (globals.HasMultiClusterNetwork)
                {
                    options.HasMultiClusterNetwork            = true;
                    options.BackgroundGossipInterval          = globals.BackgroundGossipInterval;
                    options.DefaultMultiCluster               = globals.DefaultMultiCluster?.ToList();
                    options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries;
                    options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval;
                    options.MaxMultiClusterGateways           = globals.MaxMultiClusterGateways;
                    options.UseGlobalSingleInstanceByDefault  = globals.UseGlobalSingleInstanceByDefault;
                    foreach (GlobalConfiguration.GossipChannelConfiguration channelConfig in globals.GossipChannels)
                    {
                        options.GossipChannels.Add(GlobalConfiguration.Remap(channelConfig.ChannelType), channelConfig.ConnectionString);
                    }
                }
            });

            services.TryAddFromExisting <IMessagingConfiguration, GlobalConfiguration>();

            services.AddOptions <SiloStatisticsOptions>()
            .Configure <NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options))
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.DeploymentLoadPublisherRefreshTime = config.DeploymentLoadPublisherRefreshTime;
            });

            services.AddOptions <LoadSheddingOptions>()
            .Configure <NodeConfiguration>((options, nodeConfig) =>
            {
                options.LoadSheddingEnabled = nodeConfig.LoadSheddingEnabled;
                options.LoadSheddingLimit   = nodeConfig.LoadSheddingLimit;
            });

            // Translate legacy configuration to new Options
            services.AddOptions <SiloMessagingOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                LegacyConfigurationExtensions.CopyCommonMessagingOptions(config, options);
                options.SiloSenderQueues                = config.SiloSenderQueues;
                options.GatewaySenderQueues             = config.GatewaySenderQueues;
                options.MaxForwardCount                 = config.MaxForwardCount;
                options.ClientDropTimeout               = config.ClientDropTimeout;
                options.ClientRegistrationRefresh       = config.ClientRegistrationRefresh;
                options.MaxRequestProcessingTime        = config.MaxRequestProcessingTime;
                options.AssumeHomogenousSilosForTesting = config.AssumeHomogenousSilosForTesting;
            })
            .Configure <NodeConfiguration>((options, config) =>
            {
                options.PropagateActivityId            = config.PropagateActivityId;
                LimitValue requestLimit                = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
                options.MaxEnqueuedRequestsSoftLimit   = requestLimit.SoftLimitThreshold;
                options.MaxEnqueuedRequestsHardLimit   = requestLimit.HardLimitThreshold;
                LimitValue statelessWorkerRequestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER);
                options.MaxEnqueuedRequestsSoftLimit_StatelessWorker = statelessWorkerRequestLimit.SoftLimitThreshold;
                options.MaxEnqueuedRequestsHardLimit_StatelessWorker = statelessWorkerRequestLimit.HardLimitThreshold;
            });

            services.Configure <NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options));

            services.AddOptions <EndpointOptions>()
            .Configure <IOptions <SiloOptions> >((options, siloOptions) =>
            {
                var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
                if (options.IPAddress == null && string.IsNullOrWhiteSpace(options.HostNameOrIPAddress))
                {
                    options.IPAddress = nodeConfig.Endpoint.Address;
                    options.Port      = nodeConfig.Endpoint.Port;
                }
                if (options.ProxyPort == 0 && nodeConfig.ProxyGatewayEndpoint != null)
                {
                    options.ProxyPort = nodeConfig.ProxyGatewayEndpoint.Port;
                }
            });

            services.Configure <SerializationProviderOptions>(options =>
            {
                options.SerializationProviders        = configuration.Globals.SerializationProviders;
                options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider;
            });

            services.Configure <TelemetryOptions>(options =>
            {
                LegacyConfigurationExtensions.CopyTelemetryOptions(configuration.Defaults.TelemetryConfiguration, services, options);
            });

            services.AddOptions <GrainClassOptions>().Configure <IOptions <SiloOptions> >((options, siloOptions) =>
            {
                var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
                options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes);
            });

            LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, services);

            services.AddOptions <SchedulingOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.AllowCallChainReentrancy = config.AllowCallChainReentrancy;
                options.PerformDeadlockDetection = config.PerformDeadlockDetection;
            })
            .Configure <NodeConfiguration>((options, nodeConfig) =>
            {
                options.MaxActiveThreads            = nodeConfig.MaxActiveThreads;
                options.DelayWarningThreshold       = nodeConfig.DelayWarningThreshold;
                options.ActivationSchedulingQuantum = nodeConfig.ActivationSchedulingQuantum;
                options.TurnWarningLengthThreshold  = nodeConfig.TurnWarningLengthThreshold;
                options.EnableWorkerThreadInjection = nodeConfig.EnableWorkerThreadInjection;
                LimitValue itemLimit = nodeConfig.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS);
                options.MaxPendingWorkItemsSoftLimit = itemLimit.SoftLimitThreshold;
                options.MaxPendingWorkItemsHardLimit = itemLimit.HardLimitThreshold;
            });

            services.AddOptions <GrainCollectionOptions>().Configure <GlobalConfiguration>((options, config) =>
            {
                options.CollectionQuantum = config.CollectionQuantum;
                options.CollectionAge     = config.Application.DefaultCollectionAgeLimit;
                foreach (GrainTypeConfiguration grainConfig in config.Application.ClassSpecific)
                {
                    if (grainConfig.CollectionAgeLimit.HasValue)
                    {
                        options.ClassSpecificCollectionAge.Add(grainConfig.FullTypeName, grainConfig.CollectionAgeLimit.Value);
                    }
                }
                ;
            });

            services.TryAddSingleton <LegacyProviderConfigurator.ScheduleTask>(sp =>
            {
                OrleansTaskScheduler scheduler    = sp.GetRequiredService <OrleansTaskScheduler>();
                SystemTarget fallbackSystemTarget = sp.GetRequiredService <FallbackSystemTarget>();
                return((taskFunc) => scheduler.QueueTask(taskFunc, fallbackSystemTarget.SchedulingContext));
            });
            LegacyProviderConfigurator <ISiloLifecycle> .ConfigureServices(configuration.Globals.ProviderConfigurations, services, SiloDefaultProviderInitStage, SiloDefaultProviderStartStage);

            services.AddOptions <GrainPlacementOptions>().Configure <GlobalConfiguration>((options, config) =>
            {
                options.DefaultPlacementStrategy            = config.DefaultPlacementStrategy;
                options.ActivationCountPlacementChooseOutOf = config.ActivationCountBasedPlacementChooseOutOf;
            });

            services.AddOptions <StaticClusterDeploymentOptions>().Configure <ClusterConfiguration>((options, config) =>
            {
                options.SiloNames = config.Overrides.Keys.ToList();
            });

            // add grain service configs as keyed services
            short id = 0;

            foreach (IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
            {
                services.AddSingletonKeyedService <long, IGrainServiceConfiguration>(id++, (sp, k) => grainServiceConfiguration);
            }
            // populate grain service options
            id = 0;
            services.AddOptions <GrainServiceOptions>().Configure <GlobalConfiguration>((options, config) =>
            {
                foreach (IGrainServiceConfiguration grainServiceConfiguration in config.GrainServiceConfigurations.GrainServices.Values)
                {
                    options.GrainServices.Add(new KeyValuePair <string, short>(grainServiceConfiguration.ServiceType, id++));
                }
            });

            services.AddOptions <ConsistentRingOptions>().Configure <GlobalConfiguration>((options, config) =>
            {
                options.UseVirtualBucketsConsistentRing = config.UseVirtualBucketsConsistentRing;
                options.NumVirtualBucketsConsistentRing = config.NumVirtualBucketsConsistentRing;
            });

            services.AddOptions <MembershipOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.NumMissedTableIAmAliveLimit = config.NumMissedTableIAmAliveLimit;
                options.LivenessEnabled             = config.LivenessEnabled;
                options.ProbeTimeout                = config.ProbeTimeout;
                options.TableRefreshTimeout         = config.TableRefreshTimeout;
                options.DeathVoteExpirationTimeout  = config.DeathVoteExpirationTimeout;
                options.IAmAliveTablePublishTimeout = config.IAmAliveTablePublishTimeout;
                options.MaxJoinAttemptTime          = config.MaxJoinAttemptTime;
                options.ExpectedClusterSize         = config.ExpectedClusterSize;
                options.ValidateInitialConnectivity = config.ValidateInitialConnectivity;
                options.NumMissedProbesLimit        = config.NumMissedProbesLimit;
                options.UseLivenessGossip           = config.UseLivenessGossip;
                options.NumProbedSilos              = config.NumProbedSilos;
                options.NumVotesForDeathDeclaration = config.NumVotesForDeathDeclaration;
            })
            .Configure <ClusterConfiguration>((options, config) =>
            {
                options.IsRunningAsUnitTest = config.IsRunningAsUnitTest;
            });

            services.AddOptions <ReminderOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.ReminderService          = GlobalConfiguration.Remap(config.ReminderServiceType);
                options.ReminderTableAssembly    = config.ReminderTableAssembly;
                options.UseMockReminderTable     = config.UseMockReminderTable;
                options.MockReminderTableTimeout = config.MockReminderTableTimeout;
            });

            services.AddOptions <GrainVersioningOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.DefaultCompatibilityStrategy   = config.DefaultCompatibilityStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_COMPATABILITY_STRATEGY;
                options.DefaultVersionSelectorStrategy = config.DefaultVersionSelectorStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_VERSION_SELECTOR_STRATEGY;
            });

            services.AddOptions <ThreadPoolOptions>()
            .Configure <NodeConfiguration>((options, config) =>
            {
                options.MinDotNetThreadPoolSize = config.MinDotNetThreadPoolSize;
            });

            services.AddOptions <ServicePointOptions>()
            .Configure <NodeConfiguration>((options, config) =>
            {
                options.DefaultConnectionLimit = config.DefaultConnectionLimit;
                options.Expect100Continue      = config.Expect100Continue;
                options.UseNagleAlgorithm      = config.UseNagleAlgorithm;
            });

            services.AddOptions <StorageOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.DataConnectionString             = config.DataConnectionString;
                options.DataConnectionStringForReminders = config.DataConnectionStringForReminders;
            });

            services.AddOptions <AdoNetOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.Invariant             = config.AdoInvariant;
                options.InvariantForReminders = config.AdoInvariantForReminders;
            });

            services.AddOptions <TypeManagementOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.TypeMapRefreshInterval = config.TypeMapRefreshInterval;
            });

            services.AddOptions <GrainDirectoryOptions>()
            .Configure <GlobalConfiguration>((options, config) =>
            {
                options.CachingStrategy         = GlobalConfiguration.Remap(config.DirectoryCachingStrategy);
                options.CacheSize               = config.CacheSize;
                options.InitialCacheTTL         = config.InitialCacheTTL;
                options.MaximumCacheTTL         = config.MaximumCacheTTL;
                options.CacheTTLExtensionFactor = config.CacheTTLExtensionFactor;
                options.LazyDeregistrationDelay = config.DirectoryLazyDeregistrationDelay;
            });

            return(services);
        }