Ejemplo n.º 1
0
        /// <summary>
        /// Create a local connect only ClientBuilder
        /// </summary>
        /// <param name="gatewayPort"></param>
        /// <param name="serviceId"></param>
        /// <param name="clusterId"></param>
        /// <param name="applicationPartTypes">Application parts (optional)</param>
        /// <returns></returns>
        public static IClientBuilder CreateLocalhostClientBuilder(
            int gatewayPort  = 30000,
            string clusterId = "dev",
            string serviceId = "dev",
            IEnumerable <Type> applicationPartTypes = null)
        {
            var clientBuilder = new ClientBuilder()
                                .Configure <StatisticsOptions>(options =>
            {
                options.CollectionLevel = StatisticsLevel.Critical;
            })
                                .UseLocalhostClustering(gatewayPort, serviceId, clusterId);

            if (applicationPartTypes != null)
            {
                clientBuilder.ConfigureApplicationParts(manager =>
                {
                    foreach (var applicationPartType in applicationPartTypes)
                    {
                        manager.AddApplicationPart(applicationPartType.Assembly).WithReferences();
                    }
                });
            }

            return(clientBuilder);
        }
Ejemplo n.º 2
0
        public static IClusterClient Initialize(ClientConfiguration config, int initializeAttemptsBeforeFailing = 5)
        {
            var            attempt = 0;
            IClusterClient client  = null;

            while (attempt < initializeAttemptsBeforeFailing)
            {
                try
                {
                    var builder = new ClientBuilder().ConfigureAppConfiguration();

                    builder.ConfigureApplicationParts(parts => parts.AddFromApplicationBaseDirectory());

                    client = builder.Build();
                    client.Connect().Wait();

                    break;
                }
                catch (Exception ex) when(ex is AggregateException || ex is SiloUnavailableException)
                {
                    attempt++;
                    Console.WriteLine($"Attempt {attempt} of {initializeAttemptsBeforeFailing} failed to initialize the Orleans client.");
                    if (attempt > initializeAttemptsBeforeFailing)
                    {
                        throw;
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(2));
                }

                attempt++;
            }
            return(client);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initialize Static Route ClientBuilder
        /// </summary>
        /// <param name="clusterInfo"></param>
        /// <param name="staticGatewayOption"></param>
        /// <param name="applicationPartTypes">Application parts (optional)</param>
        /// <returns></returns>
        public static IClientBuilder CreateStaticRouteClientBuilder(
            ClusterInfoOption clusterInfo,
            StaticGatewayListProviderOptions staticGatewayOption,
            IEnumerable <Type> applicationPartTypes = null)
        {
            var clientBuilder = new ClientBuilder()
                                .ConfigureCluster(clusterInfo, TimeSpan.FromSeconds(20), TimeSpan.FromMinutes(60))
                                .Configure <StatisticsOptions>(options =>
            {
                options.CollectionLevel = StatisticsLevel.Critical;
            })
                                .UseStaticClustering(option =>
            {
                option.Gateways = staticGatewayOption.Gateways;
            });

            if (applicationPartTypes != null)
            {
                clientBuilder.ConfigureApplicationParts(manager =>
                {
                    foreach (var applicationPartType in applicationPartTypes)
                    {
                        manager.AddApplicationPart(applicationPartType.Assembly).WithReferences();
                    }
                });
            }

            return(clientBuilder);
        }
Ejemplo n.º 4
0
        private static async Task <IClusterClient> TryConnect(HostBuilderContext context)
        {
            IClusterClient client = null;

            try
            {
                var builder = new ClientBuilder();

                // TODO get from context.config
                builder.UseLocalhostClustering();

                // TODO needs config delegates to customize parts
                builder.ConfigureApplicationParts(parts =>
                {
                    parts.AddApplicationPart(typeof(IArrayGrain <>).Assembly).WithReferences();
                });

                client = builder.Build();

                // causes host builder to run hosted services???
                Console.WriteLine("Awaiting connect request.");
                await client.Connect();
            }
            catch
            {
                Console.WriteLine("Exception caught.");
                client?.Dispose();
                throw;
            }

            return(client);
        }
Ejemplo n.º 5
0
        public GraphManager(string connectionString, LoggerType loggers, LogLevel logLevel, string instrumentationKey = null)
        {
            //use storage provider
            var builder = new ClientBuilder();

            builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPiSystem).Assembly));

            AddStorageProvider(builder, connectionString);
            AddAppInsighlts(builder, loggers, instrumentationKey);
            AddLoggers(builder, loggers, logLevel, instrumentationKey);
            this.client = builder.Build();
            this.client.Connect(CreateRetryFilter()).GetAwaiter().GetResult();
        }
Ejemplo n.º 6
0
        protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return(new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>

                                            new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                {
                    ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

                    var serviceName = new Uri("fabric:/RWProtoTwo/RiftRunServerService");

                    var builder = new ClientBuilder();

                    builder.Configure <ClusterOptions>(options =>
                    {
                        options.ServiceId = serviceName.ToString();
                        options.ClusterId = "RitRunProto";
                    });

                    builder.UseAzureStorageClustering(options => options.ConnectionString = ConnectionString);

                    builder.ConfigureApplicationParts(parts =>
                    {
                        parts.AddFromApplicationBaseDirectory();
                    });

                    var client = builder.Build();

                    ConnectToServer(client);

                    var accountManager = client.GetGrain <IAccountOrchestrator>("AccountOrchestrator");   //activate Orchestrator

                    accountManager.CreateAccountOrchestrator();

                    return new WebHostBuilder()
                    .UseKestrel()
                    .ConfigureServices(services =>
                    {
                        services.AddSingleton <StatelessServiceContext>(serviceContext);
                        services.AddSingleton <IClusterClient>(client);
                    })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup <Startup>()
                    .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                    .UseUrls(url)
                    .Build();
                }))
            });
        }
Ejemplo n.º 7
0
        private static async Task <IClusterClient> StartClientWithRetries()
        {
            attempt = 0;

            var clientBuilder = new ClientBuilder();

            if (_providerInfo.DefaultProvider == "MongoDB")
            {
                clientBuilder.UseMongoDBClustering(options =>
                {
                    var mongoSetting         = _providerInfo.MongoDB.Cluster;
                    options.ConnectionString = mongoSetting.DbConn;
                    options.DatabaseName     = mongoSetting.DbName;

                    // see:https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/54
                    options.CollectionPrefix = mongoSetting.CollectionPrefix;
                })
                .Configure <ClientMessagingOptions>(options => {
                    options.ResponseTimeout             = TimeSpan.FromSeconds(20);
                    options.ResponseTimeoutWithDebugger = TimeSpan.FromMinutes(60);
                })
                .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "HelloWorldApp";
                });
            }


            clientBuilder.ConfigureApplicationParts(manager =>
            {
                manager.AddApplicationPart(typeof(IVisitTracker).Assembly).WithReferences();
            })
            .ConfigureLogging(builder =>
            {
                builder.AddSerilog(dispose: true);
            });
            var client = clientBuilder.Build();

            await client.Connect(RetryFilter);

            Console.WriteLine("Client successfully connect to silo host");

            return(client);
        }
        private async Task <IClusterClient> ConfigurationClusterClient(string serviceId)
        {
            var clientBuilder = new ClientBuilder();

            if (this._environment.EnvironmentName == Environments.Development)
            {
                clientBuilder.UseLocalhostClustering(serviceId: this._options.ClusterId, clusterId: serviceId.ToLower());
            }
            else
            {
                clientBuilder.UseZooKeeperClustering(zooKeeperOptions =>
                {
                    zooKeeperOptions.ConnectionString = this._options.ZooKeeperConnectionString;
                });
            }

            var clusterClient = clientBuilder
                                //.Configure<ClusterOptions>(options =>
                                //{
                                //    options.ClusterId = this._options.ClusterId;
                                //    options.ServiceId = serviceId.ToLower();
                                //})
                                .ConfigureApplicationParts(part =>
            {
                part.AddApplicationPart(Assembly.GetExecutingAssembly());
            })
                                .ConfigureServices(service =>
            {
                service.AddLogger(this._loggingFactory)
                .AddMicrosoftLogging()
                .AddSingleton(this._mediator);
            })
                                .ConfigureLogging(configure => configure.SetMinimumLevel(this._environment.EnvironmentName == Environments.Development ? LogLevel.Debug : LogLevel.Information))
                                .Build();

            this._logging.Info($"begin connect Orleans client");
            await clusterClient.Connect(ex =>
            {
                return(Task.FromResult(true));
            });

            this._logging.Info($"OrleansClient:{clusterClient.ToJsonString()}");
            return(clusterClient);
        }
        public IUdfsClusterClient Build(
            UdfsClusterClientOptions clusterClientOptions
            )
        {
            var clientBuilder = new ClientBuilder();

            // Local or distribute cluster
            if (clusterClientOptions.Membership.Enabled)
            {
                clientBuilder.UseAdoNetClustering(
                    options =>
                {
                    options.Invariant        = clusterClientOptions.Membership.Provider;
                    options.ConnectionString = clusterClientOptions.Membership.ConnectionString;
                }
                    );
            }
            else
            {
                clientBuilder.UseLocalhostClustering();
            }

            //.ConfigureLogging(logging => logging.AddConsole())
            //.UsePerfCounterEnvironmentStatistics()
            //.Configure<ClientMessagingOptions>(options => options.ResponseTimeout = TimeSpan.FromSeconds(30))
            clientBuilder.Configure <ClusterOptions>(
                options =>
            {
                options.ClusterId = clusterClientOptions.ClusterService.ClusterId;
                options.ServiceId = clusterClientOptions.ClusterService.ServiceId;
            }
                );

            // Interfaces
            foreach (var item in clusterClientOptions.GrainAssemblies)
            {
                clientBuilder.ConfigureApplicationParts(parts => parts.AddApplicationPart(item).WithReferences());
            }

            // Build client
            return(new UdfsClusterClient(clusterClientOptions, clientBuilder.Build()));
        }
        public SerializationTestEnvironment(ClientConfiguration config = null, Action <IClientBuilder> configureClientBuilder = null)
        {
            if (config == null)
            {
                config = this.DefaultConfig();
            }

            var builder = new ClientBuilder()
                          .ConfigureDefaults()
                          .ConfigureApplicationParts(
                parts => parts
                .AddFromApplicationBaseDirectory()
                .AddFromAppDomain());

            builder.UseConfiguration(config);
            builder.ConfigureApplicationParts(parts => parts.AddFromAppDomain().AddFromApplicationBaseDirectory());
            configureClientBuilder?.Invoke(builder);
            this.Client        = builder.Build();
            this.RuntimeClient = this.Client.ServiceProvider.GetRequiredService <OutsideRuntimeClient>();
        }
Ejemplo n.º 11
0
        IClusterClient Build()
        {
            using (Trace.Execution("Orleans client initialization"))
            {
                var builder = new ClientBuilder()
                              .UseConfiguration(configuration)
                              .ConfigureServices(services =>
                {
                    services.Add(ServiceDescriptor.Singleton <IActorSystem>(this));
                    services.Add(ServiceDescriptor.Singleton <IClientActorSystem>(this));
                    services.Add(ServiceDescriptor.Singleton(this));

                    di?.Invoke(services);
                });

                builder.ConfigureApplicationParts(apm => apm
                                                  .AddFromAppDomain()
                                                  .WithCodeGeneration());

                return(builder.Build());
            }
        }
Ejemplo n.º 12
0
        public static IClusterClient Get(OrleansClientConnectionOptions options)
        {
            var serviceName = new Uri(options.FabricUrl);

            var builder = new ClientBuilder();

            builder.Configure <ClusterOptions>(opt =>
            {
                opt.ServiceId = serviceName.ToString();
                opt.ClusterId = options.ClusterId;
            });

            builder.UseAzureStorageClustering(opt =>
                                              opt.ConnectionString = options.TableStorageConnectionString);

            builder.ConfigureApplicationParts(parts =>
                                              parts.AddApplicationPart(typeof(IMyFirstGrain).Assembly));

            builder.ConfigureLogging(logging => logging.AddDebug());

            var client = builder.Build();

            return(client);
        }
        public static IClusterClient Get(string fabricUrl, string azureStorageConnectionString)
        {
            var serviceName = new Uri(fabricUrl);

            var builder = new ClientBuilder();

            builder.Configure <ClusterOptions>(options =>
            {
                options.ServiceId = serviceName.ToString();
                options.ClusterId = "development";
            });

            builder.UseAzureStorageClustering(options =>
                                              options.ConnectionString = azureStorageConnectionString);

            builder.ConfigureApplicationParts(parts =>
                                              parts.AddApplicationPart(typeof(IMyFirstGrain).Assembly));

            builder.ConfigureLogging(logging => logging.AddDebug());

            var client = builder.Build();

            return(client);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initialize a normal Orleans ClientBuilder
        /// </summary>
        /// <param name="logger">Logger to log ClientBuilder operation information</param>
        /// <param name="clusterInfo"></param>
        /// <param name="providerOption"></param>
        /// <param name="applicationPartTypes">Application parts (optional)</param>
        /// <returns></returns>
        public static IClientBuilder CreateClientBuilder(ILogger logger,
                                                         ClusterInfoOption clusterInfo,
                                                         OrleansProviderOption providerOption,
                                                         IEnumerable <Type> applicationPartTypes = null)
        {
            var clientBuilder = new ClientBuilder()
                                .ConfigureCluster(clusterInfo, TimeSpan.FromSeconds(20), TimeSpan.FromMinutes(60))
                                .Configure <StatisticsOptions>(options =>
            {
                options.CollectionLevel = StatisticsLevel.Critical;
            });

            switch (providerOption.DefaultProvider.ToLower())
            {
            case "sqldb":
            {
                logger.LogTrace("Using SQL DB provider");
                var sqlDbSetting = providerOption.SQLDB.Cluster;
                try
                {
                    var helper = new ExtMethodInvoker("Orleans.Clustering.AdoNet");
                    var adoNetClusteringClientOptionsType  = helper.ExtensionLibAssembly.GetType("Orleans.Configuration.AdoNetClusteringClientOptions", true);
                    var adoNetClusteringClientOptionsValue = new Dictionary <string, object>
                    {
                        ["ConnectionString"] = sqlDbSetting.DbConn,
                        ["Invariant"]        = sqlDbSetting.Invariant ?? @"System.Data.SqlClient"
                    };
                    var configSqlDbClusteringAction =
                        CreateDelegateHelper.CreateAssignValueAction(adoNetClusteringClientOptionsType, "options", adoNetClusteringClientOptionsValue);

                    clientBuilder = helper.Invoke <IClientBuilder>(
                        new ExtMethodInfo {
                            MethodName = "UseAdoNetClustering", ExtendedType = typeof(IClientBuilder)
                        },
                        clientBuilder, configSqlDbClusteringAction);
                }
                catch (Exception ex)
                {
                    throw new SqlDbLibLoadFailedException(ex);
                }
            }
            break;

            case "mysql":
            {
                logger.LogTrace("Using MySQL DB provider");
                var mysqlDbSetting = providerOption.SQLDB.Cluster;
                try
                {
                    var helper = new ExtMethodInvoker("Orleans.Clustering.AdoNet");
                    var adoNetClusteringClientOptionsType  = helper.ExtensionLibAssembly.GetType("Orleans.Configuration.AdoNetClusteringClientOptions", true);
                    var adoNetClusteringClientOptionsValue = new Dictionary <string, object>
                    {
                        ["ConnectionString"] = mysqlDbSetting.DbConn,
                        ["Invariant"]        = mysqlDbSetting.Invariant ?? @"MySql.Data.MySqlClient"
                    };
                    var configSqlDbClusteringAction =
                        CreateDelegateHelper.CreateAssignValueAction(adoNetClusteringClientOptionsType, "options", adoNetClusteringClientOptionsValue);

                    clientBuilder = helper.Invoke <IClientBuilder>(
                        new ExtMethodInfo {
                            MethodName = "UseAdoNetClustering", ExtendedType = typeof(IClientBuilder)
                        },
                        clientBuilder, configSqlDbClusteringAction);
                }
                catch (Exception ex)
                {
                    throw new MySqlLibLoadFailedException(ex);
                }
            }
            break;

            case "mongodb":
            {
                logger.LogTrace("Using MongoDB provider...");
                var mongoSetting = providerOption.MongoDB.Cluster;
                try
                {
                    var helper = new ExtMethodInvoker("Orleans.Providers.MongoDB");
                    clientBuilder = helper.Invoke <IClientBuilder>(
                        new ExtMethodInfo {
                            MethodName = "UseMongoDBClient", ExtendedType = typeof(IClientBuilder)
                        },
                        clientBuilder, mongoSetting.DbConn);

                    var mongoDbMembershipTableOptionsType =
                        helper.ExtensionLibAssembly.GetType("Orleans.Providers.MongoDB.Configuration.MongoDBGatewayListProviderOptions", true);
                    var mongoDbMembershipTableOptionsValue = new Dictionary <string, object>
                    {
                        ["DatabaseName"] = mongoSetting.DbName
                    };
                    if (!string.IsNullOrEmpty(mongoSetting.CollectionPrefix))
                    {
                        mongoDbMembershipTableOptionsValue["CollectionPrefix"] = mongoSetting.CollectionPrefix;
                    }
                    var configMongoDbClusteringAction =
                        CreateDelegateHelper.CreateAssignValueAction(mongoDbMembershipTableOptionsType, "options", mongoDbMembershipTableOptionsValue);

                    clientBuilder = helper.Invoke <IClientBuilder>(
                        new ExtMethodInfo {
                            MethodName = "UseMongoDBClustering", ExtendedType = typeof(IClientBuilder)
                        },
                        clientBuilder, configMongoDbClusteringAction);
                }
                catch (Exception ex)
                {
                    throw new MongoDbLibLoadFailedException(ex);
                }
            }
            break;
            }

            if (applicationPartTypes != null)
            {
                clientBuilder.ConfigureApplicationParts(manager =>
                {
                    foreach (var applicationPartType in applicationPartTypes)
                    {
                        manager.AddApplicationPart(applicationPartType.Assembly).WithReferences();
                    }
                });
            }

            return(clientBuilder);
        }
Ejemplo n.º 15
0
        private static async Task Run(string[] args)
        {
            var serviceName = new Uri("fabric:/StatelessCalculatorApp/StatelessCalculatorService");

            var builder = new ClientBuilder();

            builder.Configure <ClusterOptions>(options =>
            {
                options.ServiceId = Guid.Empty;
                options.ClusterId = "dev";
            });

            // Use Service Fabric for managing cluster membership.
            builder.UseServiceFabricClustering(serviceName);

            // Add the application assemblies.
            builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ICalculatorGrain).Assembly));

            // Optional: configure logging.
            builder.ConfigureLogging(logging => logging.AddDebug());

            builder.ConfigureServices(
                services =>
            {
                // Some deployments require a custom FabricClient, eg so that cluster endpoints and certificates can be configured.
                // A pre-configured FabricClient can be injected.
                var fabricClient = new FabricClient();
                services.AddSingleton(fabricClient);
            });

            // Create the client and connect to the cluster.
            var client = builder.Build();
            await client.Connect();

            double result;

            if (args.Length < 1)
            {
                Console.WriteLine(
                    $"Usage: {Assembly.GetExecutingAssembly()} <operation> [operand]\n\tOperations: get, set, add, subtract, multiple, divide");
                return;
            }

            var value = args.Length > 1 ? double.Parse(args[1]) : 0;

            var calculator        = client.GetGrain <ICalculatorGrain>(Guid.Empty);
            var observer          = new CalculatorObserver();
            var observerReference = await client.CreateObjectReference <ICalculatorObserver>(observer);

            var cancellationTokenSource = new CancellationTokenSource();
            var subscriptionTask        = StaySubscribed(calculator, observerReference, cancellationTokenSource.Token);

            switch (args[0].ToLower())
            {
            case "stress":
                result = await StressTest(client);

                break;

            case "add":
            case "+":
                result = await calculator.Add(value);

                break;

            case "subtract":
            case "-":
                result = await calculator.Subtract(value);

                break;

            case "multiply":
            case "*":
                result = await calculator.Multiply(value);

                break;

            case "divide":
            case "/":
                result = await calculator.Divide(value);

                break;

            case "set":
                result = await calculator.Set(value);

                break;

            case "get":
            default:
                result = await calculator.Get();

                break;
            }

            Console.WriteLine(result);
            Console.WriteLine("Listening for updates to calculations. Press any key to exit.");
            Console.ReadKey();
            cancellationTokenSource.Cancel();
            await subscriptionTask;
        }
Ejemplo n.º 16
0
        protected override void ProcessRecord()
        {
            try
            {
                this.WriteVerbose($"[{DateTime.UtcNow}] Initializing Orleans Grain Client");
                var builder = new ClientBuilder();
                switch (this.ParameterSetName)
                {
                case FilePathSet:
                    this.WriteVerbose($"[{DateTime.UtcNow}] Using config file at '{this.ConfigFilePath}'...");
                    if (string.IsNullOrWhiteSpace(this.ConfigFilePath))
                    {
                        throw new ArgumentNullException(nameof(this.ConfigFilePath));
                    }
                    builder.LoadConfiguration(this.ConfigFilePath);
                    break;

                case FileSet:
                    this.WriteVerbose($"[{DateTime.UtcNow}] Using provided config file...");
                    if (this.ConfigFile == null)
                    {
                        throw new ArgumentNullException(nameof(this.ConfigFile));
                    }
                    builder.LoadConfiguration(this.ConfigFile);
                    break;

                case ConfigSet:
                    this.WriteVerbose($"[{DateTime.UtcNow}] Using provided 'ClientConfiguration' object...");
                    if (this.Config == null)
                    {
                        throw new ArgumentNullException(nameof(this.Config));
                    }
                    builder.UseConfiguration(this.Config);
                    break;

                case EndpointSet:
                    this.WriteVerbose($"[{DateTime.UtcNow}] Using default Orleans Grain Client initializer");
                    if (this.GatewayAddress == null)
                    {
                        throw new ArgumentNullException(nameof(this.GatewayAddress));
                    }
                    var config = this.GetOverriddenConfig();
                    builder.UseConfiguration(config);
                    break;

                default:
                    this.WriteVerbose($"[{DateTime.UtcNow}] Using default Orleans Grain Client initializer");
                    builder.LoadConfiguration();
                    break;
                }

                this.client = builder
                              .ConfigureApplicationParts(parts => parts.AddFromAppDomain())
                              .Build();
                this.client.Connect().GetAwaiter().GetResult();
                this.SetClient(this.client);
                this.WriteObject(this.client);
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, ex.GetType().Name, ErrorCategory.InvalidOperation, this));
            }
        }
Ejemplo n.º 17
0
        private static async Task Run(string[] args)
        {
            var serviceName = new Uri("fabric:/StatelessCalculatorApp/StatelessCalculatorService");

            var builder = new ClientBuilder();

            builder.Configure <ClusterOptions>(options =>
            {
                options.ServiceId = serviceName.ToString();
                options.ClusterId = "development";
            });

            // TODO: Pick a clustering provider and configure it here.
            builder.UseAzureStorageClustering(options => options.ConnectionString = "UseDevelopmentStorage=true");

            // Add the application assemblies.
            builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ICalculatorGrain).Assembly));

            // Optional: configure logging.
            builder.ConfigureLogging(logging => logging.AddDebug());

            // Create the client and connect to the cluster.
            var client = builder.Build();
            await client.Connect();

            double result;

            if (args.Length < 1)
            {
                Console.WriteLine(
                    $"Usage: {Assembly.GetExecutingAssembly()} <operation> [operand]\n\tOperations: get, set, add, subtract, multiple, divide");
                return;
            }

            var value = args.Length > 1 ? double.Parse(args[1]) : 0;

            var calculator        = client.GetGrain <ICalculatorGrain>(Guid.Empty);
            var observer          = new CalculatorObserver();
            var observerReference = await client.CreateObjectReference <ICalculatorObserver>(observer);

            var cancellationTokenSource = new CancellationTokenSource();
            var subscriptionTask        = StaySubscribed(calculator, observerReference, cancellationTokenSource.Token);

            switch (args[0].ToLower())
            {
            case "stress":
                result = await StressTest(client);

                break;

            case "add":
            case "+":
                result = await calculator.Add(value);

                break;

            case "subtract":
            case "-":
                result = await calculator.Subtract(value);

                break;

            case "multiply":
            case "*":
                result = await calculator.Multiply(value);

                break;

            case "divide":
            case "/":
                result = await calculator.Divide(value);

                break;

            case "set":
                result = await calculator.Set(value);

                break;

            case "get":
            default:
                result = await calculator.Get();

                break;
            }

            Console.WriteLine(result);
            Console.WriteLine("Listening for updates to calculations. Press any key to exit.");
            Console.ReadKey();
            cancellationTokenSource.Cancel();
            await subscriptionTask;
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            listeners = new Dictionary <int, UdpServerListener>();
            sources   = new Dictionary <int, CancellationTokenSource>();

            OrleansConfig orleansConfig = GetOrleansConfig();

            config = GetPiraeusConfig();

            if (!orleansConfig.Dockerized)
            {
                var client = new ClientBuilder();
                client.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPiSystem).Assembly));
                client.UseLocalhostClustering();
                clusterClient = client.Build();
                hostname      = "localhost";
            }
            else
            {
                clusterClient = GetClient(orleansConfig);
                hostname      = Dns.GetHostName();
            }

            Task connectTask = ConnectAsync();

            Task.WhenAll(connectTask);

            int[] ports = config.GetPorts();

            foreach (var port in ports)
            {
                sources.Add(port, new CancellationTokenSource());
            }

            //string hostname = config.Hostname == null ? "localhost" : config.Hostname;

            int index = 0;

            while (index < ports.Length)
            {
                listeners.Add(ports[index], new UdpServerListener(config, new IPEndPoint(GetIPAddress(hostname), ports[index]), sources[ports[index]].Token));
                index++;
            }

            KeyValuePair <int, UdpServerListener>[] udpKvps = listeners.ToArray();

            foreach (var item in udpKvps)
            {
                item.Value.OnError += Listener_OnError;
                Task task = item.Value.StartAsync();
                Task.WhenAll(task);
            }

            done = new ManualResetEventSlim(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                done.Set();
                eventArgs.Cancel = true;
            };

            Console.WriteLine("UDP Gateway is ready...");
            done.Wait();
        }
Ejemplo n.º 19
0
        private async Task <IClusterClient> StartClientWithRetries()
        {
            var          attempt = 0;
            const int    initializeAttemptsBeforeFailing = 5;
            const double retryWaitSeconds = 4.0;

            var clientBuilder = new ClientBuilder();

            if (_providerInfo.DefaultProvider == "MongoDB")
            {
                clientBuilder.UseMongoDBClustering(options =>
                {
                    var mongoSetting         = _providerInfo.MongoDB.Cluster;
                    options.ConnectionString = mongoSetting.DbConn;
                    options.DatabaseName     = mongoSetting.DbName;

                    // see:https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/54
                    options.CollectionPrefix = mongoSetting.CollectionPrefix;
                })
                .Configure <ClientMessagingOptions>(options =>
                {
                    options.ResponseTimeout             = TimeSpan.FromSeconds(20);
                    options.ResponseTimeoutWithDebugger = TimeSpan.FromMinutes(60);
                })
                .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "HelloWorldApp";
                });
            }

            clientBuilder.ConfigureApplicationParts(manager =>
            {
                manager.AddApplicationPart(typeof(IPlayerAggregate).Assembly).WithReferences();
                manager.AddApplicationPart(typeof(IPlayer).Assembly).WithReferences();
                manager.AddApplicationPart(typeof(IGameHost).Assembly).WithReferences();
                manager.AddApplicationPart(typeof(ILeaderBoard).Assembly).WithReferences();
            })
            .ConfigureLogging(builder =>
            {
                builder.AddSerilog(dispose: true);
            });
            var client = clientBuilder.Build();

            await client.Connect(RetryFilter);

            _logger.LogInformation("Player Orleans Client successfully connect to silo host");

            return(client);

            #region Orleans Connect Retry Filter
            async Task <bool> RetryFilter(Exception exception)
            {
                if (exception.GetType() != typeof(SiloUnavailableException))
                {
                    _logger.LogError($"Cluster client failed to connect to cluster with unexpected error.  Exception: {exception}");
                    return(false);
                }

                attempt++;

                _logger.LogInformation($"Cluster client attempt {attempt} of {initializeAttemptsBeforeFailing} failed to connect to cluster.  Exception: {exception}");

                if (attempt > initializeAttemptsBeforeFailing)
                {
                    return(false);
                }

                await Task.Delay(TimeSpan.FromSeconds(retryWaitSeconds));

                return(true);
            }

            #endregion
        }