public void StorageOptionsValidator(string connectionString)
        {
            var siloPort    = 11111;
            int gatewayPort = 30000;
            var siloAddress = IPAddress.Loopback;

            var builder = new SiloHostBuilder();

            Assert.Throws <OrleansConfigurationException>(() =>
            {
                var silo = builder
                           .Configure <ClusterOptions>(options => options.ClusterId         = "TESTCLUSTER")
                           .UseDevelopmentClustering(options => options.PrimarySiloEndpoint = new IPEndPoint(siloAddress, siloPort))
                           .ConfigureEndpoints(siloAddress, siloPort, gatewayPort)
                           .ConfigureApplicationParts(pm =>
                {
                    pm.AddApplicationPart(typeof(JsonTestGrain).Assembly);
                    pm.AddApplicationPart(typeof(IJsonTestGrain).Assembly);
                })
                           .AddRedisGrainStorage("Redis", optionsBuilder => optionsBuilder.Configure(options =>
                {
                    options.ConnectionString = connectionString;
                }))
                           .Build();
            });
        }
Example #2
0
 protected Task RunSilo()
 {
     try
     {
         var builder = new SiloHostBuilder();
         builder.Configure <EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback)
         .UseLocalhostClustering()
         .Configure <ClusterOptions>(options =>
         {
             options.ClusterId = TableRoom.GameConstant.ClusterId;
             options.ServiceId = TableRoom.GameConstant.ServiceId;
         })
         .Configure <GrainCollectionOptions>(options =>
         {
             options.CollectionAge       = TimeSpan.FromSeconds(61);
             options.DeactivationTimeout = TimeSpan.FromSeconds(5);
             options.CollectionQuantum   = TimeSpan.FromSeconds(1);
         })
         .ConfigureLogging(log => log.SetMinimumLevel(LogLevel.Error).AddConsole());//LogLevel.Warning
         builder.ConfigureApplicationParts(parts =>
         {
             parts.AddApplicationPart(typeof(GChatRoomEntry).Assembly).WithReferences();
         });
         m_Host = builder.Build();
         m_Host.StartAsync().Wait();
     }
     catch (Exception e)
     {
         Log.Debug(e.ToString());
     }
     return(Task.CompletedTask);
 }
Example #3
0
        public SiloWrapper(IConfiguration config, ISemanticLog log)
        {
            this.log = log;

            silo = new Lazy <ISiloHost>(() =>
            {
                J.Serializer = SerializationServices.DefaultJsonSerializer;

                var hostBuilder = new SiloHostBuilder()
                                  .UseDashboard(options => options.HostSelf = true)
                                  .AddStartupTask <Bootstrap <IContentSchedulerGrain> >()
                                  .AddStartupTask <Bootstrap <IEventConsumerManagerGrain> >()
                                  .AddStartupTask <Bootstrap <IRuleDequeuerGrain> >()
                                  .AddStartupTask((services, ct) =>
                {
                    services.RunInitialization();

                    return(TaskHelper.Done);
                })
                                  .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "squidex";
                })
                                  .ConfigureLogging((hostingContext, builder) =>
                {
                    builder.AddConfiguration(hostingContext.Configuration.GetSection("logging"));
                    builder.AddSemanticLog();
                    builder.AddFilter("Orleans.Runtime.SiloControl", LogLevel.Warning);
                })
                                  .ConfigureApplicationParts(builder =>
                {
                    builder.AddApplicationPart(SquidexEntities.Assembly);
                    builder.AddApplicationPart(SquidexInfrastructure.Assembly);
                })
                                  .ConfigureServices((context, services) =>
                {
                    services.AddAppSiloServices(context.Configuration);
                    services.AddAppServices(context.Configuration);

                    services.Configure <ProcessExitHandlingOptions>(options => options.FastKillOnProcessExit = false);
                })
                                  .ConfigureAppConfiguration((hostContext, builder) =>
                {
                    if (config is IConfigurationRoot root)
                    {
                        foreach (var provider in root.Providers)
                        {
                            builder.Add(new Source(provider));
                        }
                    }
                });

                config.ConfigureByOption("orleans:clustering", new Options
                {
                    ["MongoDB"] = () =>
                    {
                        hostBuilder.ConfigureEndpoints(Dns.GetHostName(), 11111, 40000, listenOnAnyHostAddress: true);

                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        hostBuilder.UseMongoDBClustering(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    },
                    ["Development"] = () =>
                    {
                        hostBuilder.UseLocalhostClustering(gatewayPort: 40000, clusterId: "squidex");
                        hostBuilder.Configure <ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
                    }
                });

                config.ConfigureByOption("store:type", new Options
                {
                    ["MongoDB"] = () =>
                    {
                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        hostBuilder.UseMongoDBReminders(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    }
                });

                return(hostBuilder.Build());
            });
        }
        private ISiloHost CreateSiloHost()
        {
            var builder = new SiloHostBuilder();

            if (_dashboardOptions.Value.Enable)
            {
                builder.UseDashboard(options =>
                {
                    options.Port = _dashboardOptions.Value.Port;
                });
            }

            builder.Configure <ClusterOptions>(options =>
            {
                options.ClusterId = _siloOptions.Value.ClusterId;
                options.ServiceId = _siloOptions.Value.ServiceId;
            });

            if (string.IsNullOrEmpty(_siloOptions.Value.AdvertisedIp) || "*".Equals(_siloOptions.Value.AdvertisedIp))
            {
                builder.ConfigureEndpoints(_siloOptions.Value.SiloPort, _siloOptions.Value.GatewayPort,
                                           listenOnAnyHostAddress: _siloOptions.Value.ListenOnAnyHostAddress);
            }
            else
            {
                var ip = IPAddress.Parse(_siloOptions.Value.AdvertisedIp);

                builder.ConfigureEndpoints(ip, _siloOptions.Value.SiloPort, _siloOptions.Value.GatewayPort,
                                           listenOnAnyHostAddress: _siloOptions.Value.ListenOnAnyHostAddress);
            }

            if (_providerOptions.Value.DefaultProvider == "MongoDB")
            {
                var mongoDbOption = _providerOptions.Value.MongoDB;
                builder.UseMongoDBClustering(options =>
                {
                    var clusterOption = mongoDbOption.Cluster;

                    options.ConnectionString = clusterOption.DbConn;
                    options.DatabaseName     = clusterOption.DbName;

                    // see:https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/54
                    options.CollectionPrefix = clusterOption.CollectionPrefix;
                })
                .UseMongoDBReminders(options =>
                {
                    var reminderOption = mongoDbOption.Reminder;

                    options.ConnectionString = reminderOption.DbConn;
                    options.DatabaseName     = reminderOption.DbName;

                    if (!string.IsNullOrEmpty(reminderOption.CollectionPrefix))
                    {
                        options.CollectionPrefix = reminderOption.CollectionPrefix;
                    }
                })
                .AddMongoDBGrainStorageAsDefault(options =>
                {
                    var storageOption = mongoDbOption.Storage;

                    options.ConnectionString = storageOption.DbConn;
                    options.DatabaseName     = storageOption.DbName;

                    if (!string.IsNullOrEmpty(storageOption.CollectionPrefix))
                    {
                        options.CollectionPrefix = storageOption.CollectionPrefix;
                    }
                });
            }

            builder.ConfigureServices(services =>
            {
                services
                .AddLogging(loggingBuilder => loggingBuilder.AddSerilog())
                .AddTransient <GameHost>()
                .AddTransient <LeaderBoard>()
                .AddTransient <Player>();
            })
            .ConfigureApplicationParts(parts => { parts.AddFromApplicationBaseDirectory().WithReferences(); })
            .ConfigureLogging(logging => { logging.AddSerilog(dispose: true); });

            return(builder.Build());
        }
        private ISiloHostBuilder InitBuilder()
        {
            var hostBuilder = new SiloHostBuilder();

            hostBuilder.Configure <SerializationProviderOptions>(options =>
            {
                options.SerializationProviders.Add(typeof(OrleansCustomSerialization));

                // A workaround for an Orleans issue
                // to ensure the stack trace properly de/serialized
                // Gigya.Microdot.UnitTests.Serialization.ExceptionSerializationTests
                options.SerializationProviders.Add(typeof(NonSerializedExceptionsSerializer));

                options.FallbackSerializationProvider = typeof(OrleansCustomSerialization);
            })
            .UsePerfCounterEnvironmentStatistics()
            // We paid attention that AddFromApplicationBaseDirectory making issues of non-discovering grain types.
            .ConfigureApplicationParts(parts => parts.AddFromAppDomain())
            .Configure <SiloOptions>(options => options.SiloName = _appInfo.Name);

            if (_orleansConfig.Dashboard.Enable)
            {
                hostBuilder.UseDashboard(o =>
                {
                    o.Port = _endPointDefinition.SiloDashboardPort;
                    o.CounterUpdateIntervalMs = (int)TimeSpan.Parse(_orleansConfig.Dashboard.WriteInterval).TotalMilliseconds;
                    o.HideTrace = _orleansConfig.Dashboard.HideTrace;
                });
            }

            SetGrainCollectionOptions(hostBuilder);

            hostBuilder.Configure <PerformanceTuningOptions>(options =>
            {
                options.DefaultConnectionLimit = ServicePointManager.DefaultConnectionLimit;
            });
            hostBuilder.AddMemoryGrainStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME, options => options.NumStorageGrains = 10);
            hostBuilder.Configure <TelemetryOptions>(o => o.AddConsumer <MetricsStatisticsConsumer>());
            hostBuilder.Configure <SchedulingOptions>(options =>
            {
                options.PerformDeadlockDetection = true;
                options.AllowCallChainReentrancy = true;
                options.MaxActiveThreads         = Process.GetCurrentProcess().ProcessorAffinityList().Count();
            });

            hostBuilder.Configure <ClusterMembershipOptions>(options =>
            {
            });

            if (_orleansConfig.EnableTls)
            {
                var localCertificate = _certificateLocator.GetCertificate("Service");
                hostBuilder.UseTls(localCertificate, tlsOptions =>
                {
                    tlsOptions.LocalCertificate      = localCertificate;
                    tlsOptions.ClientCertificateMode = RemoteCertificateMode.AllowCertificate;
                    tlsOptions.RemoteCertificateMode = RemoteCertificateMode.AllowCertificate;

                    tlsOptions.SslProtocols = SslProtocols.Tls12;

                    tlsOptions.OnAuthenticateAsClient = OnAuthenticateAsClient;
                });
            }

            SetReminder(hostBuilder);
            SetSiloSource(hostBuilder);

            hostBuilder.Configure <StatisticsOptions>(o =>
            {
                o.LogWriteInterval          = TimeSpan.FromDays(1);
                o.PerfCountersWriteInterval = TimeSpan.Parse(_orleansConfig.MetricsTableWriteInterval);
            });

            return(hostBuilder);
        }
Example #6
0
        public SiloWrapper(IConfiguration config, ISemanticLog log, IApplicationLifetime lifetime)
        {
            this.lifetime = lifetime;
            this.log      = log;

            lazySilo = new Lazy <ISiloHost>(() =>
            {
                var hostBuilder = new SiloHostBuilder()
                                  .UseDashboard(options => options.HostSelf = false)
                                  .EnableDirectClient()
                                  .AddIncomingGrainCallFilter <LocalCacheFilter>()
                                  .AddStartupTask <InitializerStartup>()
                                  .AddStartupTask <Bootstrap <IContentSchedulerGrain> >()
                                  .AddStartupTask <Bootstrap <IEventConsumerManagerGrain> >()
                                  .AddStartupTask <Bootstrap <IRuleDequeuerGrain> >()
                                  .AddStartupTask <Bootstrap <IUsageTrackerGrain> >()
                                  .Configure <ClusterOptions>(options =>
                {
                    options.Configure();
                })
                                  .ConfigureApplicationParts(builder =>
                {
                    builder.AddMyParts();
                })
                                  .ConfigureLogging((hostingContext, builder) =>
                {
                    builder.AddConfiguration(hostingContext.Configuration.GetSection("logging"));
                    builder.AddSemanticLog();
                    builder.AddFilter();
                })
                                  .ConfigureServices((context, services) =>
                {
                    services.AddAppSiloServices(context.Configuration);
                    services.AddAppServices(context.Configuration);

                    services.Configure <ProcessExitHandlingOptions>(options => options.FastKillOnProcessExit = false);
                })
                                  .ConfigureAppConfiguration((hostContext, builder) =>
                {
                    if (config is IConfigurationRoot root)
                    {
                        foreach (var provider in root.Providers)
                        {
                            builder.Add(new Source(provider));
                        }
                    }
                });

                config.ConfigureByOption("orleans:clustering", new Options
                {
                    ["MongoDB"] = () =>
                    {
                        hostBuilder.ConfigureEndpoints(Dns.GetHostName(), 11111, 40000, listenOnAnyHostAddress: true);

                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        hostBuilder.UseMongoDBClustering(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    },
                    ["Development"] = () =>
                    {
                        hostBuilder.UseLocalhostClustering(gatewayPort: 40000, serviceId: Constants.OrleansClusterId, clusterId: Constants.OrleansClusterId);
                        hostBuilder.Configure <ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
                    }
                });

                config.ConfigureByOption("store:type", new Options
                {
                    ["MongoDB"] = () =>
                    {
                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        hostBuilder.UseMongoDBReminders(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    }
                });

                var silo = hostBuilder.Build();

                silo.Stopped.ContinueWith(x =>
                {
                    if (!isStopping)
                    {
                        lifetime.StopApplication();
                    }
                });

                return(silo);
            });
        }
Example #7
0
        public static IServiceProvider AddAndBuildOrleans(this IServiceCollection services, IConfiguration config, Action <IServiceCollection> afterServices)
        {
            services.Configure <ClusterOptions>(options =>
            {
                options.Configure();
            });

            services.Configure <ProcessExitHandlingOptions>(options =>
            {
                options.FastKillOnProcessExit = false;
            });

            services.AddServicesForSelfHostedDashboard(null, options =>
            {
                options.HideTrace = true;
            });

            services.AddHostedService <SiloHost>();

            var hostBuilder = new SiloHostBuilder()
                              .UseDashboardEx()
                              .EnableDirectClient()
                              .AddIncomingGrainCallFilter <LocalCacheFilter>()
                              .AddStartupTask <Bootstrap <IContentSchedulerGrain> >()
                              .AddStartupTask <Bootstrap <IEventConsumerManagerGrain> >()
                              .AddStartupTask <Bootstrap <IRuleDequeuerGrain> >()
                              .AddStartupTask <Bootstrap <IUsageTrackerGrain> >()
                              .ConfigureApplicationParts(builder =>
            {
                builder.AddMyParts();
            });

            var gatewayPort = config.GetOptionalValue("orleans:gatewayPort", 40000);

            var siloPort = config.GetOptionalValue("orleans:siloPort", 11111);

            config.ConfigureByOption("orleans:clustering", new Options
            {
                ["MongoDB"] = () =>
                {
                    hostBuilder.ConfigureEndpoints(Dns.GetHostName(), siloPort, gatewayPort, listenOnAnyHostAddress: true);

                    var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                    hostBuilder.UseMongoDBClustering(options =>
                    {
                        options.ConnectionString = mongoConfiguration;
                        options.CollectionPrefix = "Orleans_";
                        options.DatabaseName     = mongoDatabaseName;
                    });
                },
                ["Development"] = () =>
                {
                    hostBuilder.UseLocalhostClustering(siloPort, gatewayPort, null, Constants.OrleansClusterId, Constants.OrleansClusterId);
                    hostBuilder.Configure <ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
                }
            });

            config.ConfigureByOption("store:type", new Options
            {
                ["MongoDB"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                    hostBuilder.UseMongoDBReminders(options =>
                    {
                        options.ConnectionString = mongoConfiguration;
                        options.CollectionPrefix = "Orleans_";
                        options.DatabaseName     = mongoDatabaseName;
                    });
                }
            });

            IServiceProvider provider = null;

            hostBuilder.UseServiceProviderFactory((siloServices) =>
            {
                foreach (var descriptor in services)
                {
                    siloServices.Add(descriptor);
                }

                afterServices(siloServices);

                provider = siloServices.BuildServiceProvider();

                return(provider);
            }).Build();

            return(provider);
        }
Example #8
0
        private static ISiloHost ConfigureSilo()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.json", true, true)
                          .AddJsonFile($"appsettings.{EnvironmentName}.json", true, true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var siloHostBuilder = new SiloHostBuilder();

            BsonClassMap.RegisterClassMap <AccountEvent>(cm =>
            {
                cm.AutoMap();
                cm.SetIsRootClass(true);
            });

            BsonClassMap.RegisterClassMap <AccountNameEvent>();
            BsonClassMap.RegisterClassMap <DepositEvent>();
            BsonClassMap.RegisterClassMap <NewStakeholderEvent>();
            BsonClassMap.RegisterClassMap <NewTransactionEvent>();
            BsonClassMap.RegisterClassMap <WithdrawEvent>();
            IMongoDatabase database;


            siloHostBuilder.Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "dev";
                options.ServiceId = "bancor-silohost";
            });

            switch (EnvironmentName)
            {
            case "Integration":
                siloHostBuilder
                .UseConsulClustering(options => { options.Address = new Uri("http://consul:8500"); })
                .ConfigureEndpoints(siloPort: 11111, gatewayPort: 30000);
                database = new MongoDbFactory().Create();
                break;

            case "Development":
                siloHostBuilder
                .UseLocalhostClustering()
                .Configure <EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback);
                database = new MongoDbFactory().Create("mongodb://localhost:27017");
                break;

            default:
                throw new Exception($"Unknown environment '{EnvironmentName}'");
            }


            siloHostBuilder.Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "dev";
                options.ServiceId = "bancor";
            })
            .ConfigureServices(s => s.TryAddSingleton <IGrainStorage, MongoCustomerStorageProvider>())
            .ConfigureServices(s => s.TryAddTransient <ICustomerRepository, CustomerRepository>())
            .ConfigureServices(s => s.TryAddSingleton(database))
            .ConfigureServices(s => s.TryAddTransient <IJournaldAccountRepository, JournalAccountRepository>())
            .ConfigureServices(s =>
                               s.AddSingletonNamedService <IGrainStorage>("CustomerStorageProvider",
                                                                          (x, y) => new MongoCustomerStorageProvider(database,
                                                                                                                     (IGrainFactory)x.GetService(typeof(IGrainFactory)))))
            .ConfigureLogging(logging => logging.AddConsole())
            .AddMemoryGrainStorageAsDefault()
            .AddSimpleMessageStreamProvider("SMSProvider")
            .AddMemoryGrainStorage("PubSubStore")
            .AddCustomStorageBasedLogConsistencyProvider("CustomStorage")
            .UseTransactions();

            var host = siloHostBuilder.Build();

            return(host);
        }