private static async Task <ISiloHost> StartSilo()
        {
            // define the cluster configuration
            var config = new ClusterConfiguration();

            config.Defaults.Port     = new Random(1).Next(10001, 10100);
            config.Globals.ClusterId = "testcluster";
            config.AddMemoryStorageProvider();
            config.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.Disabled;

            var builder = new SiloHostBuilder()
                          .UseConfiguration(config)
                          .UseKubeMembership(opt =>
            {
                //opt.APIEndpoint = "http://localhost:8001";
                //opt.CertificateData = "test";
                //opt.APIToken = "test";
                opt.CanCreateResources  = true;
                opt.DropResourcesOnInit = true;
            })
                          .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(HelloGrain).Assembly).WithReferences())
                          .ConfigureLogging(logging => logging.AddConsole());

            var host = builder.Build();
            await host.StartAsync();

            return(host);
        }
Ejemplo n.º 2
0
 private static void AdjustConfig(ClusterConfiguration config)
 {
     // register stream provider
     config.AddMemoryStorageProvider("PubSubStore");
     config.Globals.RegisterStreamProvider <TestEventHubStreamProvider>(StreamProviderName, BuildProviderSettings());
     config.Globals.ClientDropTimeout = TimeSpan.FromSeconds(5);
 }
Ejemplo n.º 3
0
        private static ClusterConfiguration LoadClusterConfiguration()
        {
            var cluster = new ClusterConfiguration();

            cluster.LoadFromFile("OrleansConfiguration.dev.xml");
            cluster.AddMemoryStorageProvider();
            return(cluster);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initialise cluster configuration using configuration supplied or using default configuration
        /// </summary>
        /// <param name="clusterConfiguration">Used if not null</param>
        /// <returns></returns>
        public int Initialise(ClusterConfiguration clusterConfiguration = null)
        {
            if (clusterConfiguration == null)
            {
                _clusterConfiguration = ClusterConfiguration.LocalhostPrimarySilo();
                _clusterConfiguration.AddMemoryStorageProvider();
                _clusterConfiguration.AddMemoryStorageProvider("PubSubStore");
                _clusterConfiguration.AddSimpleMessageStreamProvider(MemoryChatConfiguration.MemoryChatStreamProvider);
                //_clusterConfiguration.AddAzureTableStorageProvider("AzureStore", "UseDevelopmentStorage=true");
            }
            else
            {
                _clusterConfiguration = clusterConfiguration;
            }

            return(0);
        }
Ejemplo n.º 5
0
        private static int StartSilo(string[] args)
        {
            // define the cluster configuration
            var config = new ClusterConfiguration();

            config.LoadFromFile("OrleansConfiguration.dev.xml");
            config.AddMemoryStorageProvider();
            config.UseStartupType <Startup>();

            hostWrapper = new OrleansHostWrapper(config, args);
            return(hostWrapper.Run());
        }
Ejemplo n.º 6
0
        private static int StartSilo(string[] args)
        {
            // define the cluster configuration
            var config = new ClusterConfiguration();

            config.Globals.LivenessType         = GlobalConfiguration.LivenessProviderType.AzureTable;
            config.Globals.ReminderServiceType  = GlobalConfiguration.ReminderServiceProviderType.AzureTable;
            config.Globals.DataConnectionString = "MY_DATA_CONNECTION_STRING";
            config.AddMemoryStorageProvider();
            config.AddAzureTableStorageProvider("AzureStore");
            config.Defaults.DefaultTraceLevel = Severity.Error;
            config.Defaults.Port = 100;
            config.Defaults.ProxyGatewayEndpoint = new IPEndPoint(config.Defaults.Endpoint.Address, 101);

            hostWrapper = new OrleansHostWrapper(config, args);
            return(hostWrapper.Run());
        }
Ejemplo n.º 7
0
        private static void Main()
        {
            OrleansStartup       orleansStartup = new OrleansStartup("clusterName");
            ClusterConfiguration siloConfig     = ClusterConfiguration
                                                  .LocalhostPrimarySilo(PortUtils.FindAvailablePortIncrementally(22222), PortUtils.FindAvailablePortIncrementally(40000))
                                                  .AddPublishSubscribeStreamProvider();

            siloConfig.AddMemoryStorageProvider("PubSubStore");
            ISiloHost siloHost = new SiloHostBuilder()
                                 .AddApplicationPart(typeof(TestGrain).Assembly)
                                 .UseConfiguration(siloConfig)
                                 .UseServiceProviderFactory(collection => orleansStartup.ConfigureServices(collection))
                                 .Build();

            ClientConfiguration clientConfiguration = ClientConfiguration
                                                      .LocalhostSilo()
                                                      .AddPublishSubscribeStreamProvider()
                                                      .ConnectTo(siloConfig);
            IClientBuilder clientBuilder = new ClientBuilder()
                                           .AddApplicationPart(typeof(TestGrain).Assembly)
                                           .UseConfiguration(clientConfiguration)
                                           .UseServiceProviderFactory(services => orleansStartup.ConfigureServices(services));

            using (orleansStartup.PublishSubscribe
                   .Observe <object>("*")
                   .Subscribe(_ => { Console.Out.WriteLine(_); }))
            {
                using (siloHost.Run())
                    using (IClusterClientEx clusterClient = clientBuilder.Run())
                    {
                        clusterClient.GetGrain <ITestGrain>(Guid.NewGuid()).Run().Wait();
                        //orleansStartup.PublishSubscribe.Publish("from Console", "Hello From Console");
                        Console.WriteLine("Press Enter to close.");
                        Console.ReadLine();
                    }
            }
        }
Ejemplo n.º 8
0
 private static void AdjustConfig(ClusterConfiguration config)
 {
     // register stream provider
     config.AddMemoryStorageProvider("PubSubStore");
     config.Globals.ClientDropTimeout = TimeSpan.FromSeconds(5);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Start a new silo in the target cluster
        /// </summary>
        /// <param name="host">The target cluster</param>
        /// <param name="type">The type of the silo to deploy</param>
        /// <param name="options">The options to use for the silo</param>
        /// <param name="instanceCount">The instance count of the silo</param>
        /// <param name="shared">The shared AppDomain to use</param>
        /// <returns>A handle to the deployed silo</returns>
        public static SiloHandle StartOrleansSilo(TestingSiloHost host, Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            // Load initial config settings, then apply some overrides below.
            ClusterConfiguration config = new ClusterConfiguration();

            try
            {
                if (options.SiloConfigFile == null)
                {
                    config.StandardLoad();
                }
                else
                {
                    config.LoadFromFile(options.SiloConfigFile.FullName);
                }
            }
            catch (FileNotFoundException)
            {
                if (options.SiloConfigFile != null &&
                    !string.Equals(options.SiloConfigFile.Name, TestingSiloOptions.DEFAULT_SILO_CONFIG_FILE, StringComparison.InvariantCultureIgnoreCase))
                {
                    // if the user is not using the defaults, then throw because the file was legitimally not found
                    throw;
                }

                config = ClusterConfiguration.LocalhostPrimarySilo();
                config.AddMemoryStorageProvider("Default");
                config.AddMemoryStorageProvider("MemoryStore");
            }

            int basePort = options.BasePort < 0 ? BasePort : options.BasePort;


            if (config.Globals.SeedNodes.Count > 0 && options.BasePort < 0)
            {
                config.PrimaryNode = config.Globals.SeedNodes[0];
            }
            else
            {
                config.PrimaryNode = new IPEndPoint(IPAddress.Loopback, basePort);
            }
            config.Globals.SeedNodes.Clear();
            config.Globals.SeedNodes.Add(config.PrimaryNode);

            if (!String.IsNullOrEmpty(host.DeploymentId))
            {
                config.Globals.DeploymentId = host.DeploymentId;
            }

            config.Defaults.PropagateActivityId = options.PropagateActivityId;
            if (options.LargeMessageWarningThreshold > 0)
            {
                config.Defaults.LargeMessageWarningThreshold = options.LargeMessageWarningThreshold;
            }

            config.Globals.LivenessType        = options.LivenessType;
            config.Globals.ReminderServiceType = options.ReminderServiceType;
            if (!String.IsNullOrEmpty(options.DataConnectionString))
            {
                config.Globals.DataConnectionString = options.DataConnectionString;
            }

            host.Globals = config.Globals;

            string siloName;

            switch (type)
            {
            case Silo.SiloType.Primary:
                siloName = "Primary";
                break;

            default:
                siloName = "Secondary_" + instanceCount.ToString(CultureInfo.InvariantCulture);
                break;
            }

            NodeConfiguration nodeConfig = config.GetOrCreateNodeConfigurationForSilo(siloName);

            nodeConfig.HostNameOrIPAddress = "loopback";
            nodeConfig.Port = basePort + instanceCount;
            nodeConfig.DefaultTraceLevel   = config.Defaults.DefaultTraceLevel;
            nodeConfig.PropagateActivityId = config.Defaults.PropagateActivityId;
            nodeConfig.BulkMessageLimit    = config.Defaults.BulkMessageLimit;

            int?gatewayport = null;

            if (nodeConfig.ProxyGatewayEndpoint != null && nodeConfig.ProxyGatewayEndpoint.Address != null)
            {
                gatewayport = (options.ProxyBasePort < 0 ? ProxyBasePort : options.ProxyBasePort) + instanceCount;
                nodeConfig.ProxyGatewayEndpoint = new IPEndPoint(nodeConfig.ProxyGatewayEndpoint.Address, gatewayport.Value);
            }

            config.Globals.ExpectedClusterSize = 2;

            config.Overrides[siloName] = nodeConfig;

            AdjustForTest(config, options);

            WriteLog("Starting a new silo in app domain {0} with config {1}", siloName, config.ToString(siloName));
            return(AppDomainSiloHandle.Create(siloName, type, config, nodeConfig, host.additionalAssemblies));
        }
Ejemplo n.º 10
0
        private bool ParseArguments(string[] args)
        {
            string deploymentId = null;

            string siloName = Dns.GetHostName(); // Default to machine name

            int argPos = 1;

            for (int i = 0; i < args.Length; i++)
            {
                string a = args[i];
                if (a.StartsWith("-") || a.StartsWith("/"))
                {
                    switch (a.ToLowerInvariant())
                    {
                    case "/?":
                    case "/help":
                    case "-?":
                    case "-help":
                        // Query usage help
                        return(false);

                    default:
                        Console.WriteLine("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                }
                else if (a.Contains("="))
                {
                    string[] split = a.Split('=');
                    if (String.IsNullOrEmpty(split[1]))
                    {
                        Console.WriteLine("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                    switch (split[0].ToLowerInvariant())
                    {
                    case "deploymentid":
                        deploymentId = split[1];
                        break;

                    default:
                        Console.WriteLine("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                }
                // unqualified arguments below
                else if (argPos == 1)
                {
                    siloName = a;
                    argPos++;
                }
                else
                {
                    // Too many command line arguments
                    Console.WriteLine("Too many command line arguments supplied: " + a);
                    return(false);
                }
            }
            //集群启动
            ClusterConfiguration config = new ClusterConfiguration();
            string configpath           = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{Path.GetFileNameWithoutExtension("OrleansConfiguration.xml")}.xml");

            if (File.Exists(configpath))
            {
                config.LoadFromFile(configpath);
            }
            else
            {
                config = ClusterConfiguration.LocalhostPrimarySilo();
            }
            config.AddMemoryStorageProvider();
            siloHost = new SiloHost(siloName, config);

            if (deploymentId != null)
            {
                siloHost.DeploymentId = deploymentId;
            }

            return(true);
        }
Ejemplo n.º 11
0
        static int Main(string[] args)
        {
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
            var    builder     = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddInMemoryCollection(new Dictionary <string, string> // add default settings, that will be overridden by commandline
            {
                { "Id", "OrleansHost" },
                { "Version", "1.0.0" },
                { "DeploymentId", "testdeploymentid" },
            })
                                 .AddCommandLine(args)
                                 .AddJsonFile($"appconfig.json", optional: true)
                                 .AddJsonFile($"appconfig.{environment}.json", optional: true)
                                 .AddEnvironmentVariables("ASPNETCORE_"); // The CloudService will pass settings (such as) the connectionstring through environment variables

            if ("Development".Equals(environment) && builder.GetFileProvider().GetFileInfo("OrleansHost.csproj").Exists)
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets <Program>();
            }

            var config = builder.Build();

            loggerFactory.AddConsole(config.GetSection("Logging"));
            loggerFactory.AddDebug();
            var logger = loggerFactory.CreateLogger <Program>();

            ClusterConfiguration clusterConfig = ClusterConfiguration.LocalhostPrimarySilo();

            clusterConfig.Globals.DeploymentId         = config["Id"];
            clusterConfig.Globals.DataConnectionString = config.GetConnectionString("DataConnectionString");
            clusterConfig.AddMemoryStorageProvider("Default");
            clusterConfig.AddMemoryStorageProvider("PubSubStore");
            clusterConfig.AddSimpleMessageStreamProvider("Default");
            clusterConfig.Defaults.DefaultTraceLevel = Orleans.Runtime.Severity.Warning;
            clusterConfig.Defaults.TraceFileName     = "";
            clusterConfig.UseStartupType <Startup>();

            var siloHost = new SiloHost(config["Id"], clusterConfig);

            try
            {
                siloHost.InitializeOrleansSilo();
                bool ok = siloHost.StartOrleansSilo(catchExceptions: false);

                if (!ok)
                {
                    logger.LogError(string.Format($"Failed to start Orleans silo '{siloHost.Name}' as a {siloHost.Type} node."));
                    return(1);
                }
            }
            catch (Exception exc)
            {
                siloHost.ReportStartupError(exc);
                return(2);
            }

            Console.WriteLine("OrleansHost is running. Press [Ctrl]-C to stop...");
            siloHost.WaitForOrleansSiloShutdown();
            // logger.LogInformation(string.Format($"Orleans silo '{siloHost.Name}' shutdown. Press [Enter]"));
            // Console.ReadLine();
            return(0);
        }
Ejemplo n.º 12
0
        static async Task Main(string[] args)
        {
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
            var    builder     = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddInMemoryCollection(new Dictionary <string, string> // add default settings, that will be overridden by commandline
            {
                { "Id", "OrleansHost" },
                { "Version", "1.0.0" },
                { "DeploymentId", "testdeploymentid" },
            })
                                 .AddCommandLine(args)
                                 .AddJsonFile($"appconfig.json", optional: true)
                                 .AddJsonFile($"appconfig.{environment}.json", optional: true)
                                 .AddEnvironmentVariables("ASPNETCORE_"); // The CloudService will pass settings (such as) the connectionstring through environment variables

            if ("Development".Equals(environment) && builder.GetFileProvider().GetFileInfo("OrleansHost.csproj").Exists)
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets <Program>();
            }

            var config = builder.Build();

            loggerFactory.AddConsole(config.GetSection("Logging"));
            loggerFactory.AddDebug();
            var logger = loggerFactory.CreateLogger <Program>();

            logger.LogWarning(string.Format($"Starting Orleans silo..."));

            ClusterConfiguration clusterConfig = ClusterConfiguration.LocalhostPrimarySilo();

            clusterConfig.Globals.DeploymentId         = config["Id"];
            clusterConfig.Globals.DataConnectionString = config.GetConnectionString("DataConnectionString");
            clusterConfig.AddMemoryStorageProvider("Default");
            clusterConfig.AddMemoryStorageProvider("PubSubStore");
            clusterConfig.AddSimpleMessageStreamProvider("Default");
            string siloName = config["Id"];

            var host = new SiloHostBuilder()
                       .UseConfiguration(clusterConfig)
                       .ConfigureSiloName(siloName)
                       .ConfigureServices(services =>
            {
                services.AddOptions();
                services.TryAdd(ServiceDescriptor.Singleton <ILoggerFactory, LoggerFactory>());
                services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger <>), typeof(Logger <>)));
                services.Configure <ConnectionStrings>(config.GetSection("ConnectionStrings"));
                string reduxConnectionString = config.GetConnectionString("ReduxConnectionString");
                services.AddSingleton(new ReduxTableStorage <CertState>(reduxConnectionString));
                services.AddSingleton(new ReduxTableStorage <UserState>(reduxConnectionString));
                services.AddSingleton(new ReduxTableStorage <CounterState>(reduxConnectionString));
            })
                       .AddApplicationPart(typeof(CounterGrain).Assembly)
                       .AddApplicationPartsFromReferences(typeof(CounterGrain).Assembly)
                       .Build();

            try
            {
                await host.StartAsync();

                logger.LogInformation(string.Format($"Successfully started Orleans silo {siloName}"));
                Console.WriteLine($"Silo {siloName} is running. Press [enter] to stop...");
                Console.ReadLine();

                await host.StopAsync();

                logger.LogWarning(string.Format($"Orleans silo shutdown."));
            }
            catch (Exception e)
            {
                logger.LogCritical(e, "Silo stopping fatally with exception: " + e.Message);
            }
        }