示例#1
0
        private static Dictionary <string, GrainTypeData> CreateGrainTypeMap(GrainClassFeature grainClassFeature, GrainClassOptions grainClassOptions)
        {
            var result = new Dictionary <string, GrainTypeData>();

            var excluded = grainClassOptions.ExcludedGrainTypes;

            foreach (var grainClassMetadata in grainClassFeature.Classes)
            {
                var grainType = grainClassMetadata.ClassType;
                var className = TypeUtils.GetFullName(grainType);

                if (excluded != null && excluded.Contains(className))
                {
                    continue;
                }

                result[className] = new GrainTypeData(grainType);
            }

            return(result);
        }
        public void RuntimeCodeGen_AddsSupportClasses()
        {
            var partManager = new ApplicationPartManager();

            partManager.AddApplicationPart(typeof(IRuntimeCodeGenGrain).Assembly);
            partManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            partManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            partManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());

            var interfaceFeature = new GrainInterfaceFeature();

            partManager.PopulateFeature(interfaceFeature);
            Assert.DoesNotContain(interfaceFeature.Interfaces, i => i.InterfaceType == typeof(IRuntimeCodeGenGrain));

            var classFeature = new GrainClassFeature();

            partManager.PopulateFeature(classFeature);
            Assert.DoesNotContain(classFeature.Classes, c => c.ClassType == typeof(RuntimeCodeGenGrain));

            var serializerFeature = new SerializerFeature();

            partManager.PopulateFeature(serializerFeature);
            Assert.DoesNotContain(serializerFeature.SerializerTypes, s => s.Target == typeof(RuntimeCodeGenPoco));

            partManager.AddApplicationPart(typeof(IRuntimeCodeGenGrain).Assembly).WithCodeGeneration();
            interfaceFeature = new GrainInterfaceFeature();
            partManager.PopulateFeature(interfaceFeature);
            Assert.Contains(interfaceFeature.Interfaces, i => i.InterfaceType == typeof(IRuntimeCodeGenGrain));

            classFeature = new GrainClassFeature();
            partManager.PopulateFeature(classFeature);
            Assert.Contains(classFeature.Classes, c => c.ClassType == typeof(RuntimeCodeGenGrain));

            serializerFeature = new SerializerFeature();
            partManager.PopulateFeature(serializerFeature);
            Assert.Contains(serializerFeature.SerializerTypes, s => s.Target == typeof(RuntimeCodeGenPoco));
        }
示例#3
0
        internal static void AddDefaultServices(IServiceCollection services)
        {
            services.AddOptions();

            services.AddTransient <IConfigurationValidator, EndpointOptionsValidator>();

            // Options logging
            services.TryAddSingleton(typeof(IOptionFormatter <>), typeof(DefaultOptionsFormatter <>));
            services.TryAddSingleton(typeof(IOptionFormatterResolver <>), typeof(DefaultOptionsFormatterResolver <>));

            // Register system services.
            services.TryAddSingleton <ILocalSiloDetails, LocalSiloDetails>();
            services.TryAddSingleton <ISiloHost, SiloHost>();
            services.TryAddTransient <ILifecycleSubject, LifecycleSubject>();
            services.TryAddSingleton <SiloLifecycleSubject>();
            services.TryAddFromExisting <ISiloLifecycleSubject, SiloLifecycleSubject>();
            services.TryAddFromExisting <ISiloLifecycle, SiloLifecycleSubject>();
            services.AddSingleton <SiloOptionsLogger>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloOptionsLogger>();
            services.PostConfigure <SiloMessagingOptions>(options =>
            {
                //
                // Assign environment specific defaults post configuration if user did not configured otherwise.
                //

                if (options.SiloSenderQueues == 0)
                {
                    options.SiloSenderQueues = Environment.ProcessorCount;
                }

                if (options.GatewaySenderQueues == 0)
                {
                    options.GatewaySenderQueues = Environment.ProcessorCount;
                }
            });
            services.TryAddSingleton <TelemetryManager>();
            services.TryAddFromExisting <ITelemetryProducer, TelemetryManager>();

            services.TryAddSingleton <IAppEnvironmentStatistics, AppEnvironmentStatistics>();
            services.TryAddSingleton <IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
            services.TryAddSingleton <SiloStatisticsManager>();
            services.TryAddSingleton <ApplicationRequestsStatisticsGroup>();
            services.TryAddSingleton <StageAnalysisStatisticsGroup>();
            services.TryAddSingleton <SchedulerStatisticsGroup>();
            services.TryAddSingleton <SerializationStatisticsGroup>();
            services.TryAddSingleton <OverloadDetector>();

            services.TryAddSingleton <FallbackSystemTarget>();
            services.TryAddSingleton <LifecycleSchedulingSystemTarget>();

            services.AddLogging();
            services.TryAddSingleton <ITimerRegistry, TimerRegistry>();
            services.TryAddSingleton <IReminderRegistry, ReminderRegistry>();
            services.AddTransient <IConfigurationValidator, ReminderOptionsValidator>();
            services.TryAddSingleton <GrainRuntime>();
            services.TryAddSingleton <IGrainRuntime, GrainRuntime>();
            services.TryAddSingleton <IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
            services.AddTransient <CancellationSourcesExtension>();
            services.AddTransientKeyedService <Type, IGrainExtension>(typeof(ICancellationSourcesExtension), (sp, _) => sp.GetRequiredService <CancellationSourcesExtension>());
            services.TryAddSingleton <OrleansTaskScheduler>();
            services.TryAddSingleton <GrainFactory>(sp => sp.GetService <InsideRuntimeClient>().ConcreteGrainFactory);
            services.TryAddSingleton <GrainInterfaceTypeToGrainTypeResolver>();
            services.TryAddFromExisting <IGrainFactory, GrainFactory>();
            services.TryAddFromExisting <IInternalGrainFactory, GrainFactory>();
            services.TryAddSingleton <IGrainReferenceRuntime, GrainReferenceRuntime>();
            services.TryAddSingleton <GrainReferenceActivator>();
            services.AddSingleton <IGrainReferenceActivatorProvider, ImrGrainReferenceActivatorProvider>();
            services.AddSingleton <IGrainReferenceActivatorProvider, UntypedGrainReferenceActivatorProvider>();
            services.AddSingleton <IConfigureGrainContextProvider, MayInterleaveConfiguratorProvider>();
            services.AddSingleton <IConfigureGrainTypeComponents, ReentrantSharedComponentsConfigurator>();
            services.TryAddSingleton <ImrRpcProvider>();
            services.TryAddSingleton <ImrGrainMethodInvokerProvider>();
            services.TryAddSingleton <GrainReferenceSerializer>();
            services.TryAddSingleton <GrainReferenceKeyStringConverter>();
            services.AddSingleton <GrainVersionManifest>();
            services.TryAddSingleton <GrainBindingsResolver>();
            services.TryAddSingleton <GrainTypeComponentsResolver>();
            services.TryAddSingleton <ActivationDirectory>();
            services.AddSingleton <ActivationCollector>();
            services.AddFromExisting <IActivationCollector, ActivationCollector>();

            // Directory
            services.TryAddSingleton <LocalGrainDirectory>();
            services.TryAddFromExisting <ILocalGrainDirectory, LocalGrainDirectory>();
            services.AddSingleton <GrainLocator>();
            services.AddSingleton <GrainLocatorResolver>();
            services.AddSingleton <DhtGrainLocator>(sp => DhtGrainLocator.FromLocalGrainDirectory(sp.GetService <LocalGrainDirectory>()));
            services.AddSingleton <GrainDirectoryResolver>();
            services.AddSingleton <IGrainDirectoryResolver, GenericGrainDirectoryResolver>();
            services.AddSingleton <CachedGrainLocator>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, CachedGrainLocator>();
            services.AddSingleton <ClientGrainLocator>();

            services.TryAddSingleton <MessageCenter>();
            services.TryAddFromExisting <IMessageCenter, MessageCenter>();
            services.TryAddSingleton(FactoryUtility.Create <MessageCenter, Gateway>);
            services.TryAddSingleton <IConnectedClientCollection>(sp => (IConnectedClientCollection)sp.GetRequiredService <MessageCenter>().Gateway ?? new EmptyConnectedClientCollection());
            services.TryAddSingleton <Dispatcher>(sp => sp.GetRequiredService <Catalog>().Dispatcher);
            services.TryAddSingleton <ActivationMessageScheduler>(sp => sp.GetRequiredService <Catalog>().ActivationMessageScheduler);
            services.TryAddSingleton <InsideRuntimeClient>();
            services.TryAddFromExisting <IRuntimeClient, InsideRuntimeClient>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, InsideRuntimeClient>();
            services.TryAddSingleton <IGrainServiceFactory, GrainServiceFactory>();

            services.TryAddSingleton <IFatalErrorHandler, FatalErrorHandler>();

            services.TryAddSingleton <DeploymentLoadPublisher>();

            services.TryAddSingleton <IAsyncTimerFactory, AsyncTimerFactory>();
            services.TryAddSingleton <MembershipTableManager>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipTableManager>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipTableManager>();
            services.TryAddSingleton <MembershipSystemTarget>();
            services.AddFromExisting <IMembershipService, MembershipSystemTarget>();
            services.TryAddSingleton <IMembershipGossiper, MembershipGossiper>();
            services.TryAddSingleton <IRemoteSiloProber, RemoteSiloProber>();
            services.TryAddSingleton <SiloStatusOracle>();
            services.TryAddFromExisting <ISiloStatusOracle, SiloStatusOracle>();
            services.AddSingleton <ClusterHealthMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterHealthMonitor>();
            services.AddFromExisting <IHealthCheckParticipant, ClusterHealthMonitor>();
            services.AddSingleton <ProbeRequestMonitor>();
            services.AddSingleton <LocalSiloHealthMonitor>();
            services.AddFromExisting <ILocalSiloHealthMonitor, LocalSiloHealthMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, LocalSiloHealthMonitor>();
            services.AddSingleton <MembershipAgent>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipAgent>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipAgent>();
            services.AddSingleton <MembershipTableCleanupAgent>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipTableCleanupAgent>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipTableCleanupAgent>();
            services.AddSingleton <SiloStatusListenerManager>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloStatusListenerManager>();
            services.AddSingleton <ClusterMembershipService>();
            services.TryAddFromExisting <IClusterMembershipService, ClusterMembershipService>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterMembershipService>();

            services.TryAddSingleton <ClientDirectory>();
            services.AddFromExisting <ILocalClientDirectory, ClientDirectory>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClientDirectory>();

            services.TryAddSingleton <SiloProviderRuntime>();
            services.TryAddFromExisting <IProviderRuntime, SiloProviderRuntime>();

            services.TryAddSingleton <MessageFactory>();

            services.TryAddSingleton(FactoryUtility.Create <GrainDirectoryPartition>);

            // Placement
            services.AddSingleton <IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
            services.AddSingleton <PlacementService>();
            services.AddSingleton <PlacementStrategyResolver>();
            services.AddSingleton <PlacementDirectorResolver>();
            services.AddSingleton <IPlacementStrategyResolver, ClientObserverPlacementStrategyResolver>();

            // Configure the default placement strategy.
            services.TryAddSingleton <PlacementStrategy, RandomPlacement>();

            // Placement directors
            services.AddPlacementDirector <RandomPlacement, RandomPlacementDirector>();
            services.AddPlacementDirector <PreferLocalPlacement, PreferLocalPlacementDirector>();
            services.AddPlacementDirector <StatelessWorkerPlacement, StatelessWorkerDirector>();
            services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
            services.AddPlacementDirector <ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
            services.AddPlacementDirector <HashBasedPlacement, HashBasedPlacementDirector>();
            services.AddPlacementDirector <ClientObserversPlacement, ClientObserversPlacementDirector>();

            // Activation selectors
            services.AddSingletonKeyedService <Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
            services.AddSingletonKeyedService <Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));

            // Versioning
            services.TryAddSingleton <VersionSelectorManager>();
            services.TryAddSingleton <CachedVersionSelectorManager>();
            // Version selector strategy
            if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
            {
                services.TryAddSingleton <GrainVersionStore>();
                services.AddFromExisting <IVersionStore, GrainVersionStore>();
            }
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, GrainVersionStore>();
            services.AddSingletonNamedService <VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
            services.AddSingletonNamedService <VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
            services.AddSingletonNamedService <VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
            // Versions selectors
            services.AddSingletonKeyedService <Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));

            // Compatibility
            services.TryAddSingleton <CompatibilityDirectorManager>();
            // Compatability strategy
            services.AddSingletonNamedService <CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
            // Compatability directors
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));

            services.TryAddSingleton <Factory <IGrainRuntime> >(sp => () => sp.GetRequiredService <IGrainRuntime>());

            // Grain activation
            services.TryAddSingleton <Catalog>();
            services.AddFromExisting <IHealthCheckParticipant, Catalog>();
            services.TryAddSingleton <GrainContextActivator>();
            services.AddSingleton <IConfigureGrainTypeComponents, ConfigureDefaultGrainActivator>();
            services.TryAddSingleton <GrainReferenceActivator>();
            services.TryAddSingleton <IGrainContextActivatorProvider, ActivationDataActivatorProvider>();
            services.TryAddSingleton <IGrainContextAccessor, GrainContextAccessor>();
            services.AddSingleton <IncomingRequestMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, IncomingRequestMonitor>();

            services.TryAddSingleton <IConsistentRingProvider>(
                sp =>
            {
                // TODO: make this not sux - jbragg
                var consistentRingOptions = sp.GetRequiredService <IOptions <ConsistentRingOptions> >().Value;
                var siloDetails           = sp.GetRequiredService <ILocalSiloDetails>();
                var loggerFactory         = sp.GetRequiredService <ILoggerFactory>();
                if (consistentRingOptions.UseVirtualBucketsConsistentRing)
                {
                    return(new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing));
                }

                return(new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory));
            });

            services.TryAddSingleton(typeof(IKeyedServiceCollection <,>), typeof(KeyedServiceCollection <,>));

            // Serialization
            services.TryAddSingleton <SerializationManager>(sp => ActivatorUtilities.CreateInstance <SerializationManager>(sp,
                                                                                                                           sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.LargeMessageWarningThreshold));
            services.TryAddSingleton <ITypeResolver, CachedTypeResolver>();
            services.TryAddSingleton <IFieldUtils, FieldUtils>();

            // Register the ISerializable serializer first, so that it takes precedence
            services.AddSingleton <DotNetSerializableSerializer>();
            services.AddFromExisting <IKeyedSerializer, DotNetSerializableSerializer>();


            services.AddSingleton <ILBasedSerializer>();
            services.AddFromExisting <IKeyedSerializer, ILBasedSerializer>();

            // Transactions
            services.TryAddSingleton <ITransactionAgent, DisabledTransactionAgent>();

            // Application Parts
            var applicationPartManager = services.GetApplicationPartManager();

            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
            services.AddTransient <IConfigurationValidator, ApplicationPartValidator>();

            // Type metadata
            services.AddSingleton <SiloManifestProvider>();
            services.AddSingleton <GrainClassMap>(sp => sp.GetRequiredService <SiloManifestProvider>().GrainTypeMap);
            services.AddSingleton <GrainTypeResolver>();
            services.AddSingleton <IGrainTypeProvider, AttributeGrainTypeProvider>();
            services.AddSingleton <IGrainTypeProvider, LegacyGrainTypeResolver>();
            services.AddSingleton <GrainPropertiesResolver>();
            services.AddSingleton <GrainInterfaceTypeResolver>();
            services.AddSingleton <IGrainInterfacePropertiesProvider, AttributeGrainInterfacePropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, AttributeGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, AttributeGrainBindingsProvider>();
            services.AddSingleton <IGrainInterfacePropertiesProvider, TypeNameGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, TypeNameGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, ImplementedInterfaceProvider>();
            services.AddSingleton <ClusterManifestProvider>();
            services.AddFromExisting <IClusterManifestProvider, ClusterManifestProvider>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterManifestProvider>();
            services.AddSingleton <TypeConverter>();

            //Add default option formatter if none is configured, for options which are required to be configured
            services.ConfigureFormatter <SiloOptions>();
            services.ConfigureFormatter <SchedulingOptions>();
            services.ConfigureFormatter <PerformanceTuningOptions>();
            services.ConfigureFormatter <SerializationProviderOptions>();
            services.ConfigureFormatter <ConnectionOptions>();
            services.ConfigureFormatter <SiloMessagingOptions>();
            services.ConfigureFormatter <ClusterMembershipOptions>();
            services.ConfigureFormatter <GrainDirectoryOptions>();
            services.ConfigureFormatter <ActivationCountBasedPlacementOptions>();
            services.ConfigureFormatter <GrainCollectionOptions>();
            services.ConfigureFormatter <GrainVersioningOptions>();
            services.ConfigureFormatter <ConsistentRingOptions>();
            services.ConfigureFormatter <StatisticsOptions>();
            services.ConfigureFormatter <TelemetryOptions>();
            services.ConfigureFormatter <LoadSheddingOptions>();
            services.ConfigureFormatter <EndpointOptions>();
            services.ConfigureFormatter <ClusterOptions>();

            // This validator needs to construct the IMembershipOracle and the IMembershipTable
            // so move it in the end so other validator are called first
            services.AddTransient <IConfigurationValidator, ClusterOptionsValidator>();
            services.AddTransient <IConfigurationValidator, SiloClusteringValidator>();
            services.AddTransient <IConfigurationValidator, DevelopmentClusterMembershipOptionsValidator>();

            // Enable hosted client.
            services.TryAddSingleton <HostedClient>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, HostedClient>();
            services.TryAddSingleton <InternalClusterClient>();
            services.TryAddFromExisting <IInternalClusterClient, InternalClusterClient>();
            services.TryAddFromExisting <IClusterClient, InternalClusterClient>();

            // Enable collection specific Age limits
            services.AddOptions <GrainCollectionOptions>()
            .Configure <IApplicationPartManager>((options, parts) =>
            {
                var grainClasses = new GrainClassFeature();
                parts.PopulateFeature(grainClasses);

                foreach (var grainClass in grainClasses.Classes)
                {
                    var attr = grainClass.ClassType.GetCustomAttribute <CollectionAgeLimitAttribute>();
                    if (attr != null)
                    {
                        var className = TypeUtils.GetFullName(grainClass.ClassType);
                        options.ClassSpecificCollectionAge[className] = attr.Amount;
                    }
                }
            });

            // Validate all CollectionAgeLimit values for the right configuration.
            services.AddTransient <IConfigurationValidator, GrainCollectionOptionsValidator>();

            services.AddTransient <IConfigurationValidator, LoadSheddingValidator>();

            services.TryAddSingleton <ITimerManager, TimerManagerImpl>();

            // persistent state facet support
            services.TryAddSingleton <IPersistentStateFactory, PersistentStateFactory>();
            services.TryAddSingleton(typeof(IAttributeToFactoryMapper <PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));

            // Networking
            services.TryAddSingleton <ConnectionCommon>();
            services.TryAddSingleton <ConnectionManager>();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, ConnectionManagerLifecycleAdapter <ISiloLifecycle> >();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, SiloConnectionMaintainer>();

            services.AddSingletonKeyedService <object, IConnectionFactory>(
                SiloConnectionFactory.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionFactory>(sp));
            services.AddSingletonKeyedService <object, IConnectionListenerFactory>(
                SiloConnectionListener.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionListenerFactory>(sp));
            services.AddSingletonKeyedService <object, IConnectionListenerFactory>(
                GatewayConnectionListener.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionListenerFactory>(sp));

            services.TryAddTransient <IMessageSerializer>(sp => ActivatorUtilities.CreateInstance <MessageSerializer>(sp,
                                                                                                                      sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.MaxMessageHeaderSize,
                                                                                                                      sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.MaxMessageBodySize));
            services.TryAddSingleton <ConnectionFactory, SiloConnectionFactory>();
            services.AddSingleton <NetworkingTrace>();
            services.AddSingleton <RuntimeMessagingTrace>();
            services.AddFromExisting <MessagingTrace, RuntimeMessagingTrace>();

            // Use Orleans server.
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, SiloConnectionListener>();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, GatewayConnectionListener>();
            services.AddSingleton <SocketSchedulers>();
            services.AddSingleton <SharedMemoryPool>();

            // Logging helpers
            services.AddSingleton <SiloLoggingHelper>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloLoggingHelper>();
            services.AddFromExisting <IGrainIdLoggingHelper, SiloLoggingHelper>();
            services.AddFromExisting <IInvokeMethodRequestLoggingHelper, SiloLoggingHelper>();
        }
示例#4
0
        internal static void AddDefaultServices(IApplicationPartManager applicationPartManager, IServiceCollection services)
        {
            services.AddOptions();

            services.AddTransient <IConfigurationValidator, EndpointOptionsValidator>();

            // Options logging
            services.TryAddSingleton(typeof(IOptionFormatter <>), typeof(DefaultOptionsFormatter <>));
            services.TryAddSingleton(typeof(IOptionFormatterResolver <>), typeof(DefaultOptionsFormatterResolver <>));

            // Register system services.
            services.TryAddSingleton <ILocalSiloDetails, LocalSiloDetails>();
            services.TryAddSingleton <ISiloHost, SiloWrapper>();
            services.TryAddTransient <ILifecycleSubject, LifecycleSubject>();
            services.TryAddSingleton <ISiloLifecycleSubject, SiloLifecycleSubject>();
            services.TryAddSingleton <ILifecycleParticipant <ISiloLifecycle>, SiloOptionsLogger>();
            services.PostConfigure <SiloMessagingOptions>(options =>
            {
                //
                // Assign environment specific defaults post configuration if user did not configured otherwise.
                //

                if (options.SiloSenderQueues == 0)
                {
                    options.SiloSenderQueues = Environment.ProcessorCount;
                }

                if (options.GatewaySenderQueues == 0)
                {
                    options.GatewaySenderQueues = Environment.ProcessorCount;
                }
            });
            services.TryAddSingleton <TelemetryManager>();
            services.TryAddFromExisting <ITelemetryProducer, TelemetryManager>();

            services.TryAddSingleton <IAppEnvironmentStatistics, AppEnvironmentStatistics>();
            services.TryAddSingleton <IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
            services.TryAddSingleton <SiloStatisticsManager>();
            services.TryAddSingleton <ApplicationRequestsStatisticsGroup>();
            services.TryAddSingleton <StageAnalysisStatisticsGroup>();
            services.TryAddSingleton <SchedulerStatisticsGroup>();
            services.TryAddSingleton <SerializationStatisticsGroup>();
            services.TryAddSingleton <OverloadDetector>();

            services.TryAddSingleton <ExecutorService>();
            // queue balancer contructing related
            services.TryAddTransient <IStreamQueueBalancer, ConsistentRingQueueBalancer>();
            services.TryAddSingleton <IStreamSubscriptionHandleFactory, StreamSubscriptionHandlerFactory>();

            services.TryAddSingleton <FallbackSystemTarget>();
            services.TryAddSingleton <LifecycleSchedulingSystemTarget>();

            services.AddLogging();
            services.TryAddSingleton <ITimerRegistry, TimerRegistry>();
            services.TryAddSingleton <IReminderRegistry, ReminderRegistry>();
            services.TryAddSingleton <GrainRuntime>();
            services.TryAddSingleton <IGrainRuntime, GrainRuntime>();
            services.TryAddSingleton <IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
            services.TryAddSingleton <OrleansTaskScheduler>();
            services.TryAddSingleton <GrainFactory>(sp => sp.GetService <InsideRuntimeClient>().ConcreteGrainFactory);
            services.TryAddFromExisting <IGrainFactory, GrainFactory>();
            services.TryAddFromExisting <IInternalGrainFactory, GrainFactory>();
            services.TryAddFromExisting <IGrainReferenceConverter, GrainFactory>();
            services.TryAddSingleton <IGrainReferenceRuntime, GrainReferenceRuntime>();
            services.TryAddSingleton <TypeMetadataCache>();
            services.TryAddSingleton <ActivationDirectory>();
            services.TryAddSingleton <ActivationCollector>();
            services.TryAddSingleton <LocalGrainDirectory>();
            services.TryAddFromExisting <ILocalGrainDirectory, LocalGrainDirectory>();
            services.TryAddSingleton(sp => sp.GetRequiredService <LocalGrainDirectory>().GsiActivationMaintainer);
            services.TryAddSingleton <GrainTypeManager>();
            services.TryAddSingleton <MessageCenter>();
            services.TryAddFromExisting <IMessageCenter, MessageCenter>();
            services.TryAddFromExisting <ISiloMessageCenter, MessageCenter>();
            services.TryAddSingleton(FactoryUtility.Create <MessageCenter, Gateway>);
            services.TryAddSingleton <Dispatcher>(sp => sp.GetRequiredService <Catalog>().Dispatcher);
            services.TryAddSingleton <InsideRuntimeClient>();
            services.TryAddFromExisting <IRuntimeClient, InsideRuntimeClient>();
            services.TryAddFromExisting <ISiloRuntimeClient, InsideRuntimeClient>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, InsideRuntimeClient>();

            services.TryAddSingleton <MultiClusterGossipChannelFactory>();
            services.TryAddSingleton <MultiClusterOracle>();
            services.TryAddSingleton <MultiClusterRegistrationStrategyManager>();
            services.TryAddFromExisting <IMultiClusterOracle, MultiClusterOracle>();
            services.TryAddSingleton <DeploymentLoadPublisher>();

            services.TryAddSingleton <MembershipOracle>();
            services.TryAddFromExisting <IMembershipOracle, MembershipOracle>();
            services.TryAddFromExisting <ISiloStatusOracle, MembershipOracle>();

            services.TryAddSingleton <ClientObserverRegistrar>();
            services.TryAddSingleton <SiloProviderRuntime>();
            services.TryAddFromExisting <IStreamProviderRuntime, SiloProviderRuntime>();
            services.TryAddFromExisting <IProviderRuntime, SiloProviderRuntime>();
            services.TryAddSingleton <ImplicitStreamSubscriberTable>();
            services.TryAddSingleton <MessageFactory>();

            services.TryAddSingleton <IGrainRegistrar <GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>();
            services.TryAddSingleton <IGrainRegistrar <ClusterLocalRegistration>, ClusterLocalRegistrar>();
            services.TryAddSingleton <RegistrarManager>();
            services.TryAddSingleton <Factory <Grain, IMultiClusterRegistrationStrategy, ILogConsistencyProtocolServices> >(FactoryUtility.Create <Grain, IMultiClusterRegistrationStrategy, ProtocolServices>);
            services.TryAddSingleton(FactoryUtility.Create <GrainDirectoryPartition>);

            // Placement
            services.AddSingleton <IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
            services.TryAddSingleton <PlacementDirectorsManager>();
            services.TryAddSingleton <ClientObserversPlacementDirector>();

            // Configure the default placement strategy.
            services.TryAddSingleton <PlacementStrategy, RandomPlacement>();

            // Placement directors
            services.AddPlacementDirector <RandomPlacement, RandomPlacementDirector>();
            services.AddPlacementDirector <PreferLocalPlacement, PreferLocalPlacementDirector>();
            services.AddPlacementDirector <StatelessWorkerPlacement, StatelessWorkerDirector>();
            services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
            services.AddPlacementDirector <ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
            services.AddPlacementDirector <HashBasedPlacement, HashBasedPlacementDirector>();

            // Activation selectors
            services.AddSingletonKeyedService <Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
            services.AddSingletonKeyedService <Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));

            // Versioning
            services.TryAddSingleton <VersionSelectorManager>();
            services.TryAddSingleton <CachedVersionSelectorManager>();
            // Version selector strategy
            if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
            {
                services.TryAddSingleton <GrainVersionStore>();
                services.AddFromExisting <IVersionStore, GrainVersionStore>();
            }
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, GrainVersionStore>();
            services.AddSingletonNamedService <VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
            services.AddSingletonNamedService <VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
            services.AddSingletonNamedService <VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
            // Versions selectors
            services.AddSingletonKeyedService <Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));

            // Compatibility
            services.TryAddSingleton <CompatibilityDirectorManager>();
            // Compatability strategy
            services.AddSingletonNamedService <CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
            // Compatability directors
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));

            services.TryAddSingleton <Factory <IGrainRuntime> >(sp => () => sp.GetRequiredService <IGrainRuntime>());

            // Grain activation
            services.TryAddSingleton <Catalog>();
            services.TryAddSingleton <GrainCreator>();
            services.TryAddSingleton <IGrainActivator, DefaultGrainActivator>();
            services.TryAddScoped <ActivationData.GrainActivationContextFactory>();
            services.TryAddScoped <IGrainActivationContext>(sp => sp.GetRequiredService <ActivationData.GrainActivationContextFactory>().Context);

            services.TryAddSingleton <IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService <IStreamProviderRuntime>()));
            services.TryAddSingleton <IConsistentRingProvider>(
                sp =>
            {
                // TODO: make this not sux - jbragg
                var consistentRingOptions = sp.GetRequiredService <IOptions <ConsistentRingOptions> >().Value;
                var siloDetails           = sp.GetRequiredService <ILocalSiloDetails>();
                var loggerFactory         = sp.GetRequiredService <ILoggerFactory>();
                if (consistentRingOptions.UseVirtualBucketsConsistentRing)
                {
                    return(new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing));
                }

                return(new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory));
            });

            services.TryAddSingleton(typeof(IKeyedServiceCollection <,>), typeof(KeyedServiceCollection <,>));

            // Serialization
            services.TryAddSingleton <SerializationManager>(sp => ActivatorUtilities.CreateInstance <SerializationManager>(sp,
                                                                                                                           sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.LargeMessageWarningThreshold));
            services.TryAddSingleton <ITypeResolver, CachedTypeResolver>();
            services.TryAddSingleton <IFieldUtils, FieldUtils>();
            services.AddSingleton <BinaryFormatterSerializer>();
            services.AddSingleton <BinaryFormatterISerializableSerializer>();
            services.AddFromExisting <IKeyedSerializer, BinaryFormatterISerializableSerializer>();
            services.AddSingleton <ILBasedSerializer>();
            services.AddFromExisting <IKeyedSerializer, ILBasedSerializer>();

            // Transactions
            services.TryAddSingleton <ITransactionAgent, DisabledTransactionAgent>();

            // Application Parts
            services.TryAddSingleton <IApplicationPartManager>(applicationPartManager);
            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
            services.AddTransient <IConfigurationValidator, ApplicationPartValidator>();

            //Add default option formatter if none is configured, for options which are required to be configured
            services.ConfigureFormatter <SiloOptions>();
            services.ConfigureFormatter <ProcessExitHandlingOptions>();
            services.ConfigureFormatter <SchedulingOptions>();
            services.ConfigureFormatter <PerformanceTuningOptions>();
            services.ConfigureFormatter <SerializationProviderOptions>();
            services.ConfigureFormatter <NetworkingOptions>();
            services.ConfigureFormatter <SiloMessagingOptions>();
            services.ConfigureFormatter <TypeManagementOptions>();
            services.ConfigureFormatter <ClusterMembershipOptions>();
            services.ConfigureFormatter <GrainDirectoryOptions>();
            services.ConfigureFormatter <ActivationCountBasedPlacementOptions>();
            services.ConfigureFormatter <GrainCollectionOptions>();
            services.ConfigureFormatter <GrainVersioningOptions>();
            services.ConfigureFormatter <ConsistentRingOptions>();
            services.ConfigureFormatter <MultiClusterOptions>();
            services.ConfigureFormatter <StatisticsOptions>();
            services.ConfigureFormatter <TelemetryOptions>();
            services.ConfigureFormatter <LoadSheddingOptions>();
            services.ConfigureFormatter <EndpointOptions>();

            // This validator needs to construct the IMembershipOracle and the IMembershipTable
            // so move it in the end so other validator are called first
            services.AddTransient <IConfigurationValidator, ClusterOptionsValidator>();
            services.AddTransient <IConfigurationValidator, SiloClusteringValidator>();

            // Disable hosted client by default.
            services.TryAddSingleton <IHostedClient, DisabledHostedClient>();

            // Enable collection specific Age limits
            services.AddOptions <GrainCollectionOptions>()
            .Configure <IApplicationPartManager>((options, parts) =>
            {
                var grainClasses = new GrainClassFeature();
                parts.PopulateFeature(grainClasses);

                foreach (var grainClass in grainClasses.Classes)
                {
                    var attr = grainClass.ClassType.GetCustomAttribute <CollectionAgeLimitAttribute>();
                    if (attr != null)
                    {
                        var className = TypeUtils.GetFullName(grainClass.ClassType);
                        options.ClassSpecificCollectionAge[className] = TimeSpan.FromMinutes(attr.Minutes);
                    }
                }
            });

            // Validate all CollectionAgeLimit values for the right configuration.
            services.AddTransient <IConfigurationValidator, GrainCollectionOptionsValidator>();

            services.TryAddSingleton <ITimerManager, TimerManagerImpl>();

            // persistent state facet support
            services.TryAddSingleton <IPersistentStateFactory, PersistentStateFactory>();
            services.TryAddSingleton(typeof(IAttributeToFactoryMapper <PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));
        }
        /// <inheritdoc />
        public void ValidateConfiguration()
        {
            var hasApplicationAssembly = this.applicationPartManager.ApplicationParts.OfType <AssemblyPart>().Any(part => !part.IsFrameworkAssembly);

            if (!hasApplicationAssembly)
            {
                throw new OrleansConfigurationException(
                          $"No application assemblies were added to {nameof(ApplicationPartManager)}." +
                          $" Add assemblies using the {nameof(ApplicationPartManagerExtensions.AddApplicationPart)}({nameof(Assembly)}) extension method on the client builder.");
            }

            // Ensure there is a non-framework assembly which has had code generation executed on it.
            var hasCodeGenRun = this.applicationPartManager.ApplicationParts
                                .OfType <AssemblyPart>()
                                .Any(part => !part.IsFrameworkAssembly && part.Assembly.GetCustomAttribute <FeaturePopulatorAttribute>() != null);

            if (!hasCodeGenRun)
            {
                throw new OrleansConfigurationException(
                          $"None of the assemblies added to {nameof(ApplicationPartManager)} contain generated code." +
                          " Ensure that code generation has been executed for grain interface and class assemblies.");
            }

            var allProviders      = this.applicationPartManager.FeatureProviders;
            var nonFrameworkParts = this.applicationPartManager.ApplicationParts
                                    .Where(part => !(part is AssemblyPart asm) || !asm.IsFrameworkAssembly)
                                    .ToList();

            var isSilo = this.serviceProvider.GetService(typeof(ILocalSiloDetails)) != null;

            if (isSilo)
            {
                var providers = allProviders.OfType <IApplicationFeatureProvider <GrainClassFeature> >();
                var grains    = new GrainClassFeature();
                foreach (var provider in providers)
                {
                    provider.PopulateFeature(nonFrameworkParts, grains);
                }

                var hasGrains = grains.Classes.Any();
                if (!hasGrains)
                {
                    throw new OrleansConfigurationException(
                              $"None of the assemblies added to {nameof(ApplicationPartManager)} contain generated code for grain classes." +
                              " Ensure that code generation has been executed for grain interface and grain class assemblies and that they have been added as application parts.");
                }
            }

            {
                var providers       = allProviders.OfType <IApplicationFeatureProvider <GrainInterfaceFeature> >();
                var grainInterfaces = new GrainInterfaceFeature();
                foreach (var provider in providers)
                {
                    provider.PopulateFeature(nonFrameworkParts, grainInterfaces);
                }

                bool hasGrainInterfaces = grainInterfaces.Interfaces.Any();
                if (!hasGrainInterfaces)
                {
                    throw new OrleansConfigurationException(
                              $"None of the assemblies added to {nameof(ApplicationPartManager)} contain generated code for grain interfaces." +
                              " Ensure that code generation has been executed for grain interface and grain class assemblies and that they have been added as application parts.");
                }
            }
        }