Пример #1
0
        public GrpcTestEventHost(ApplicationConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _builder       = new HostBuilder();

            _builder.ConfigureServices(services =>
            {
                services.AddGrpc();
            });
            var stuff = _builder.ConfigureServices((hostContext, services) =>
            {
                // setup the reflection support for service discovery
                var reflectionService = new ReflectionServiceImpl(TestEvent.Descriptor, ServerReflection.Descriptor);
                var testEventService  = new TestEventService(_configuration);
                testEventService.TestEventReceived += TestEventService_TestEventReceived;
                // create a Grpc server
                var server = new Server
                {
                    Services = { TestEvent.BindService(testEventService), ServerReflection.BindService(reflectionService) },
                    Ports    = { new ServerPort(GrpcServer, _configuration.Port, ServerCredentials.Insecure) },
                };
                var gprcHostedService = new GrpcHostedService(server);
                services.AddSingleton(server);
                services.AddSingleton(gprcHostedService);
                services.AddSingleton <IHostedService, GrpcHostedService>(serviceProvider => gprcHostedService);
                _serviceProvider = services.BuildServiceProvider();
            });
        }
        static async Task Main(string[] args)
        {
            Server server = null;

            try
            {
                // reflection-1
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    GreetingService.Descriptor
                    , CalculatorService.Descriptor
                    , PrimeNumberDecompositionService.Descriptor
                    , SqrtService.Descriptor
                    , DeadlineService.Descriptor
                    , ServerReflection.Descriptor
                    );

                server = new Server
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImplementation()),
                        CalculatorService.BindService(new CalculatorServiceImplementation()),
                        PrimeNumberDecompositionService.BindService(new PrimeNumberDecompositionServiceImplementation()),

                        // errors
                        SqrtService.BindService(new SqrtServiceImplementation()),
                        // deadlines
                        DeadlineService.BindService(new DeadlineServiceImplementation()),

                        // reflection-2
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        await CreateUnsecureServerPort(Host, Port)
                    }
                };

                server.Start();
                Console.WriteLine($"Server is listening on {Port}");
                Console.ReadLine();
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Server failed to start: {ex.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Server failed: {ex.Message}");
                throw;
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
        }
Пример #3
0
        public static Server AddGrpcServices(this IServiceProvider provider, ILoggerFactory loggerFactory, int port)
        {
            var servicePort = GetPort(port);

            GrpcEnvironment.SetLogger(new LogLevelFilterLogger(new GrpcLogger(loggerFactory), Grpc.Core.Logging.LogLevel.Debug));
            GrpcEnvironment.Logger.Debug($@"Starting Kickstart services on port {servicePort}");

            var server = new Server
            {
                Services =
                {
                    //Reflection used by some testers
                    KickstartBuildService.BindService(provider.GetRequiredService <KickstartBuildServiceImpl>()),
                    KickstartServiceApi.BindService(provider.GetRequiredService <KickstartServiceImpl>()),

                    ServerReflection.BindService(new ReflectionServiceImpl(KickstartServiceApi.Descriptor,       KickstartBuildService.Descriptor,
                                                                           Health.Descriptor))
                },
                Ports =
                {
                    new ServerPort("0.0.0.0", servicePort, ServerCredentials.Insecure)
                }
            };

            return(server);
        }
Пример #4
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(BlogService.Descriptor, ServerReflection.Descriptor);

                server = new Server()
                {
                    Services =
                    {
                        BlogService.BindService(new BlogServiceImpl()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine("The server is listenin on port " + port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server faild" + e.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
Пример #5
0
 static void Main(string[] args)
 {
     try
     {
         var    reflectionServiceImpl = new ReflectionServiceImpl(ProtoHubService.Descriptor, ServerReflection.Descriptor);
         Server server = new Server
         {
             Services =
             {
                 ServerReflection.BindService(reflectionServiceImpl),
                 ProtoHubService.BindService(new ProtoHubImpl())
             },
             Ports = { new ServerPort("localhost", 5000, ServerCredentials.Insecure) }
         };
         server.Start();
         Console.WriteLine("Server listening on port " + 5000);
         Console.WriteLine("Press any key to stop the server...");
         Console.ReadKey();
         server.ShutdownAsync().Wait();
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Exception encountered: {ex}");
     }
 }
Пример #6
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.CompletedTask);
            }

            var descriptors = new List <Google.Protobuf.Reflection.ServiceDescriptor>
            {
                ServerReflection.Descriptor
            };

            foreach (var grpcService in _services)
            {
                _server.Services.Add(grpcService.BindService());
                if (grpcService.Descriptor != null)
                {
                    descriptors.Add(grpcService.Descriptor);
                }
            }

            var reflectionServiceImpl = new ReflectionServiceImpl(descriptors);

            _server.Services.Add(ServerReflection.BindService(reflectionServiceImpl));
            var host = _configuration.GetValue("GrpcHost", "localhost");
            var port = _configuration.GetValue("GrpcPort", 50050);

            _server.Ports.Add(host, port, ServerCredentials.Insecure);
            _server.Start();

            return(Task.CompletedTask);
        }
Пример #7
0
        public static Server AddGrpcServices(this
                                             IServiceProvider provider,
                                             ILoggerFactory loggerFactory,
                                             IConfiguration configuration)
        {
            var servicePort = GetPort(configuration);

            GrpcEnvironment.SetLogger(new LogLevelFilterLogger(new GrpcLogger(loggerFactory), LogLevel.Debug));
            GrpcEnvironment.Logger.Debug($@"Starting Build services on port {servicePort}");

            var logger = loggerFactory.CreateLogger <LoggingInterceptor>();

            var builder = new GrpcServerBuilder()
                          .AddInsecurePort(servicePort);

            var services = new List <ServerServiceDefinition>
            {
                KickstartBuildService.BindService(provider.GetRequiredService <KickstartBuildServiceImpl>())
                .Intercept(new LoggingInterceptor(logger, Microsoft.Extensions.Logging.LogLevel.Information)),

                Health.BindService(provider.GetRequiredService <HealthServiceImpl>())
                .Intercept(new LoggingInterceptor(logger, Microsoft.Extensions.Logging.LogLevel.Debug)),
            };

            //AddTracing(provider, services, configuration);

            builder.AddServices(services);

            builder.AddService(ServerReflection.BindService(new ReflectionServiceImpl(
                                                                KickstartBuildService.Descriptor,
                                                                Health.Descriptor)));

            return(builder.Build());
        }
Пример #8
0
        public static async Task Main(string[] args)
        {
            var ip   = UtilsLibrary.NetworkUtils.GetMyIp();
            int port = int.Parse(ConfigurationManager.AppSettings.Get("port"));

            var reflectionServiceImpl = new ReflectionServiceImpl(ServersListMaker.Descriptor, ServerReflection.Descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services =
                {
                    ServersListMaker.BindService(new ServersListMakerService()),                     //для сервиса устанвливаем обработчик
                    ServerReflection.BindService(reflectionServiceImpl)
                },
                Ports = { new ServerPort(ip.ToString(), port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine($"Сервер запущен по адресу {ip}:{port}");
            Console.WriteLine("Нажмите любую клавишу для выхода");
            Console.ReadKey();
            Console.WriteLine("Сервер завершает работу");
            await server.ShutdownAsync();

            Console.WriteLine("Сервер закрыт");
            Console.ReadKey();
        }
Пример #9
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddDebug();

            ILogger logger    = loggerFactory.CreateLogger <Program>();
            var     rpcLogger = loggerFactory.CreateLogger <InventoryManagementImpl>();

            var port = int.Parse(Configuration["service:port"]);

            var          brokerList    = Configuration["kafkaclient:brokerlist"];
            const string ReservedTopic = "inventoryreserved";
            const string ReleasedTopic = "inventoryreleased";

            var config = new Dictionary <string, object>
            {
                { "group.id", "inventory-server" },
                { "enable.auto.commit", false },
                { "bootstrap.servers", brokerList }
            };
            //var context = new InventoryContext(Configuration["postgres:connectionstring"]);
            var context = new InventoryContext();
            var repo    = new InventoryRepository(context);

            var reservedEventProcessor = new InventoryReservedEventProcessor(repo);
            var kafkaConsumer          = new KafkaReservedConsumer(ReservedTopic, config, reservedEventProcessor);

            kafkaConsumer.Consume();

            var releasedEventProcessor = new InventoryReleasedEventProcessor(repo);
            var releasedConsumer       = new KafkaReleasedConsumer(ReleasedTopic, config, releasedEventProcessor);

            releasedConsumer.Consume();

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, InventoryManagement.Descriptor);
            var inventoryManagement = new InventoryManagementImpl(repo, rpcLogger);
            var server = new Server
            {
                Services = { InventoryManagement.BindService(inventoryManagement),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();
            logger.LogInformation("Inventory gRPC Service Listening on Port " + port);

            mre.WaitOne();
        }
Пример #10
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            var port = int.Parse(Configuration["service:port"]);

            var brokerList = Configuration["kafkaclient:brokerlist"];
            var config     = new Dictionary <string, object>
            {
                { "group.id", "order-command" },
                { "enable.auto.commit", "false" },
                { "bootstrap.servers", brokerList }
            };

            IEventEmitter kafkaEmitter = new KafkaEventEmitter(config, loggerFactory.CreateLogger <KafkaEventEmitter>());
            // TODO: this channel needs to use a service-discovery hostname
            var orderChannel = new Channel($"{Configuration["orderclient:hostname"]}:{Configuration["orderclient:port"]}",
                                           ChannelCredentials.Insecure);
            var inventoryChannel = new Channel($"{Configuration["inventoryclient:hostname"]}:{Configuration["inventoryclient:port"]}",
                                               ChannelCredentials.Insecure);

            logger.LogInformation($"Configured gRPC channel for Order Management client: {orderChannel.ResolvedTarget}");
            logger.LogInformation($"Configured gRPC channel for Inventory Management client: {inventoryChannel.ResolvedTarget}");

            var orderClient     = new OrderManagement.OrderManagementClient(orderChannel);
            var inventoryClient = new InventoryManagement.InventoryManagementClient(inventoryChannel);

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, OrderCommand.Descriptor);

            var rpcLogger = loggerFactory.CreateLogger <OrderCommandImpl>();
            var server    = new Server
            {
                Services = { OrderCommand.BindService(new OrderCommandImpl(rpcLogger, kafkaEmitter, orderClient, inventoryClient)),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();

            logger.LogInformation("Orders Command gRPC Service Listening on Port " + port);

            // Keep the process alive without consuming CPU cycles
            mre.WaitOne();
        }
Пример #11
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();


            Configuration = builder.Build();

            Microsoft.Extensions.Logging.ILoggerFactory loggerFactory = new LoggerFactory()
                                                                        .AddConsole()
                                                                        .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            string       brokerList    = Configuration["kafkaclient:brokerlist"];
            const string Topic         = "orders";
            const string CanceledTopic = "canceledorders";

            var config = new Dictionary <string, object>
            {
                { "group.id", "order-management" },
                { "enable.auto.commit", false },
                { "bootstrap.servers", brokerList }
            };

            var context           = new OrdersContext(Configuration["postgres:connectionstring"]);
            var repo              = new OrderRepository(context);
            var eventProcessor    = new OrderAcceptedEventProcessor(repo);
            var canceledProcessor = new OrderCanceledEventProcessor(repo);

            var orderConsumer    = new KafkaOrdersConsumer(Topic, config, eventProcessor);
            var activityConsumer = new KafkaActivitiesConsumer(CanceledTopic, config, canceledProcessor);

            orderConsumer.Consume();
            activityConsumer.Consume();

            var port = int.Parse(Configuration["service:port"]);

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, OrderManagement.Descriptor);
            Server server = new Server
            {
                Services = { OrderManagement.BindService(new OrderManagementImpl(repo)),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();
            logger.LogInformation("Order management gRPC service listening on port " + port);

            mre.WaitOne();
        }
Пример #12
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var serverCertificate  = File.ReadAllText("ssl/server.crt");
                var serverKey          = File.ReadAllText("ssl/server.key");
                var keyCertificatePair = new KeyCertificatePair(serverCertificate, serverKey);
                var caCertificate      = File.ReadAllText("ssl/ca.crt");

                var credentials = new SslServerCredentials(new List <KeyCertificatePair>()
                {
                    keyCertificatePair
                }, caCertificate, true);

                // ./evans.exe -r -p 50051
                var greetingServiceReflectionServiceImpl   = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);
                var calculatorServiceReflectionServiceImpl = new ReflectionServiceImpl(CalculatorService.Descriptor, ServerReflection.Descriptor);
                var blogServiceReflectionServiceImpl       = new ReflectionServiceImpl(BlogService.Descriptor, ServerReflection.Descriptor);

                server = new Server()
                {
                    Services =
                    {
                        BlogService.BindService(new BlogServiceImpl()),
                        ServerReflection.BindService(blogServiceReflectionServiceImpl),
                        GreetingService.BindService(new GreetingServiceImpl()),
                        //ServerReflection.BindService(greetingServiceReflectionServiceImpl),
                        CalculatorService.BindService(new CalculatorServiceImpl()),
                        //ServerReflection.BindService(calculatorServiceReflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine("The server is listening on the port :" + port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server failed to start:" + e.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
Пример #13
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            server = new Server
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports    = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
Пример #14
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);

                var serverCert = File.ReadAllText("ssl/server.crt");
                var serverKey  = File.ReadAllText("ssl/server.key");
                var keypair    = new KeyCertificatePair(serverCert, serverKey);
                var cacert     = File.ReadAllText("ssl/ca.crt");

                var credentials = new SslServerCredentials(
                    new List <KeyCertificatePair>()
                {
                    keypair
                }, cacert, true);

                server = new Server()
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImp()),
                        CalculatorService.BindService(new CalculatorServiceImp()),
                        SqrtService.BindService(new SqrtServiceImpl()),
                        GreetDeadlinesService.BindService(new GreetingDeadlinesImpl()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },

                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };

                server.Start();

                Console.WriteLine("The server is listening on the port {0}", Port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server failed to start: ", e.Message);
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var serverCert = File.ReadAllText("ssl/server.crt");
                var serverKey  = File.ReadAllText("ssl/server.key");
                var keypair    = new KeyCertificatePair(serverCert, serverKey);
                var caCrt      = File.ReadAllText("ssl/ca.crt");

                var credentials = new SslServerCredentials(new List <KeyCertificatePair>()
                {
                    keypair
                }, caCrt, true);

                server = new Server()
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImpl()),
                        SumService.BindService(new SumServiceImpl()),
                        PrimeNumbersService.BindService(new PrimeNumbersServiceImpl()),
                        AverageService.BindService(new AverageServiceImpl()),
                        MaxService.BindService(new MaxServiceImpl()),
                        SqrtService.BindService(new SquareRootServiceImpl()),
                        ServerReflection.BindService(new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor))
                    },

                    Ports = { new ServerPort("localhost", port, credentials) }
                };

                server.Start();
                Console.WriteLine($"Server is listening on port: {port}");
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine($"Server failed to start - {e.Message}");
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
Пример #16
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports    = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
Пример #17
0
        static void Main(string[] args)
        {
            //FOR SSL------------------------------------
            //var serverCert = File.ReadAllText("ssl/server.crt");
            //var serverKey = File.ReadAllText("ssl/server.key");
            //var keypair = new KeyCertificatePair(serverCert, serverKey);
            //var caCert = File.ReadAllText("ssl/ca.crt");

            //var credentials = new SslServerCredentials(new List<KeyCertificatePair>() { keypair }, caCert, true);
            //---------------------------------------------------
            //FOR REFLECTION
            var reflectionServiceImpl = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);
            //-------------------------------------------------------

            Server server = null;

            try
            {
                server = new Server()
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImpl()),
                        ServerReflection.BindService(reflectionServiceImpl) //FOR REFLECTION
                    },                                                      //it tells server when client calls greet function, it will call the implementaion of it which is GreetingServiceImpl()

                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }//WITHOUT SSL
                    //Ports = { new ServerPort("localhost", Port, credentials) }//WITH SSL
                };
                server.Start();
                Console.WriteLine("The Server is listening on Port : " + Port);
                Console.ReadKey();
            }
            catch (IOException ex)
            {
                Console.WriteLine("The Server failed to start : " + ex.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();//running synchronously here.can be asyncronous if server and client is in different system
                }
            }
        }
Пример #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(configure => configure.AddConsole());
            services.AddSingleton <AppContainer>();

            services.AddSingleton(_ => new StorageOptions(Configuration["Storage"]));

            services.AddMediatR(typeof(Startup).Assembly);
            services.AddValidators(typeof(Startup));
            services.AddBehaviorsForRequest <IDriveRequest>(typeof(Startup));
            services.AddErrorHandling(typeof(Startup));

            services.AddControllers();
            services.AddHttpContextAccessor();

            services.AddHealthChecks()
            .AddCheck <LivenessCheck>("liveness", tags: new List <string> {
                "liveness"
            })
            .AddCheck <ReadinessCheck>("readiness", tags: new List <string> {
                "readiness"
            });

            services.AddSingleton(_ =>
                                  new ValuesContainer(Configuration["SecretValue"], Configuration["NotSecretValue"]));

            services.AddSingleton(sp =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(FileService.Descriptor, ServerReflection.Descriptor);
                var server = new Server
                {
                    Services =
                    {
                        FileService.BindService(new Grpc.FileService(sp.GetService <StorageOptions>())),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", 3000, ServerCredentials.Insecure) },
                };
                return(server);
            });

            services.AddHostedService <GrpcHostedService>();
        }
        static async Task Main(string[] args)
        {
            var reflectionServiceImpl = new ReflectionServiceImpl(
                BlogService.Descriptor
                , ServerReflection.Descriptor
                );

            var server = new Server
            {
                Services =
                {
                    BlogService.BindService(new BlogServiceImpl()),
                    ServerReflection.BindService(reflectionServiceImpl),
                },
                Ports =
                {
                    new ServerPort(Host, Port, ServerCredentials.Insecure)
                }
            };

            try
            {
                server.Start();
                Console.WriteLine("Server is listening.");
                Console.ReadLine();
            }
            catch (IOException ex)
            {
                Console.WriteLine($"IO Error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
        }
Пример #20
0
        public static Grpc.Core.Server Start(string host, int port)
        {
            var descriptor = Greeter.Descriptor;

            Console.WriteLine("Starting gRPC server, descriptor=" + descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services =
                {
                    Greeter.BindService(new GreeterService()),                                                               //grpc service
                    ServerReflection.BindService(new ReflectionServiceImpl(Greeter.Descriptor, ServerReflection.Descriptor)) //grpc service reflection (https://github.com/grpc/grpc/blob/master/doc/csharp/server_reflection.md) (no proto file needed for gRPCurl...)
                },
                Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
            };
            server.Start();
            Console.WriteLine($"Started gRPC server at http://{host}:{port}");

            return(server);
        }
Пример #21
0
        public static void Main(string[] args)
        {
            var    reflectionServiceImpl = new ReflectionServiceImpl(Greeter.Descriptor, ServerReflection.Descriptor);
            Server server = new Server
            {
                Services =
                {
                    // the server will serve 2 services, the Greeter and the ServerReflection
                    Greeter.BindService(new GreeterImpl()),
                    ServerReflection.BindService(reflectionServiceImpl)
                },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
Пример #22
0
        static void Main(string[] args)
        {
            var serverCert        = File.ReadAllText("../../../ssl/server.crt");
            var serverKey         = File.ReadAllText("../../../ssl/server.key");
            var caCert            = File.ReadAllText("../../../ssl/ca.crt");
            var channelCredential = new SslServerCredentials(new List <KeyCertificatePair> {
                new KeyCertificatePair(serverCert, serverKey)
            }, caCert, true);
            var serviceDesc = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services = { GreetingService.BindService(new GreetingServiceImpl()),
                             PrimeNumberDecomposition.BindService(new PrimeNumberDecompositionServiceImpl()),
                             SquareRootService.BindService(new SquareRootServiceImpl()),
                             ServerReflection.BindService(serviceDesc) },
                //Ports = { new ServerPort("localhost", 5000, ServerCredentials.Insecure) }
                Ports = { new ServerPort("localhost", 5000, channelCredential) }
            };
            server.Start();
            Console.WriteLine("server started...");
            Console.ReadLine();
        }
Пример #23
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                server = new Server()
                {
                    Services =
                    {
                        FindMaxService.BindService(new FindMaxServiceImplementation()),
                        ServerReflection.BindService(new ReflectionServiceImpl(new List <ServiceDescriptor>()
                        {
                            FindMaxService.Descriptor
                        }))
                    },
                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };

                server.Start();
                Console.WriteLine($"The server is listening on the port: {Port}");
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine($"Something went wrong - {e.Message}");
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
Пример #24
0
        static async Task Main(string[] args)
        {
            var server = new Grpc.Core.Server
            {
                Services =
                {
                    ServerReflection.BindService(new ReflectionServiceImpl(GreeterServiceReflection.Descriptor.Services)),
                    Health.BindService(new HealthServiceImpl()),

                    GreeterService
                    .BindService(new GreeterServiceImplementation())
                    .Intercept(new SimpleInterceptor())
                },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            await server.ShutdownAsync();
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .AutoActivate()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    MarketDataService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        MarketDataService.BindService(
                            new MarketDataServiceClient(ctx.Resolve <RedisService>())),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", _appSettings.CurrentValue.MarketDataService.GrpcPort,
                                       ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.Register(c =>
            {
                var lazy = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_appSettings.CurrentValue.MarketDataService.Redis.Configuration));
                return(lazy.Value);
            })
            .As <IConnectionMultiplexer>()
            .SingleInstance();

            builder.Register(c => c.Resolve <IConnectionMultiplexer>().GetDatabase())
            .As <IDatabase>();

            builder.RegisterMarketProfileClient(_appSettings.CurrentValue.MarketDataService.MarketProfileUrl);

            builder.RegisterInstance(
                new Candleshistoryservice(new Uri(_appSettings.CurrentValue.MarketDataService.CandlesHistoryUrl))
                ).As <ICandleshistoryservice>().SingleInstance();

            builder.RegisterType <InitService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <QuotesFeedSubscriber>()
            .WithParameter(new NamedParameter("connectionString", _appSettings.CurrentValue.MarketDataService.RabbitMq.QuotesConnectionString))
            .WithParameter(new NamedParameter("exchangeName", _appSettings.CurrentValue.MarketDataService.RabbitMq.QuotesExchangeName))
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <LimitOrdersSubscriber>()
            .WithParameter(new NamedParameter("connectionString", _appSettings.CurrentValue.MarketDataService.RabbitMq.LimitOrdersConnectionString))
            .WithParameter(new NamedParameter("exchangeName", _appSettings.CurrentValue.MarketDataService.RabbitMq.LimitOrdersExchangeName))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .AsSelf()
            .SingleInstance();

            builder.RegisterAssetsClient(_appSettings.CurrentValue.AssetsServiceClient);

            builder.RegisterType <RedisService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .SingleInstance();

            builder.RegisterType <CleanupHandler>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .As <IStartable>()
            .AutoActivate()
            .SingleInstance();

            builder.Register(ctx =>
            {
                return(_appSettings.CurrentValue.MarketDataService.MyNoSqlServer.Enabled
                    ? new MyNoSqlServer.DataWriter.MyNoSqlServerDataWriter <Ticker>(() =>
                                                                                    _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.ServiceUrl,
                                                                                    _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.TickersTableName)
                    : (IMyNoSqlServerDataWriter <Ticker>) new MockNoSqlServerDataWriter <Ticker>());
            }).As <IMyNoSqlServerDataWriter <Ticker> >().SingleInstance();

            builder.Register(ctx =>
            {
                return(_appSettings.CurrentValue.MarketDataService.MyNoSqlServer.Enabled
                    ? new MyNoSqlServer.DataWriter.MyNoSqlServerDataWriter <Price>(() =>
                                                                                   _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.ServiceUrl,
                                                                                   _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.PricesTableName)
                    : (IMyNoSqlServerDataWriter <Price>) new MockNoSqlServerDataWriter <Price>());
            }).As <IMyNoSqlServerDataWriter <Price> >().SingleInstance();
        }
Пример #26
0
        private static void RunServer(Options options)
        {
            var hostName = options.Hostname ?? Dns.GetHostName();

            var serviceDescriptors = new [] { Dlink.Descriptor, Health.Descriptor, ServerReflection.Descriptor };
            var greeterImpl        = new DlinkImpl(hostName);
            var healthServiceImpl  = new HealthServiceImpl();
            var reflectionImpl     = new ReflectionServiceImpl(serviceDescriptors);

            Server server = new Server
            {
                Services = { Dlink.BindService(greeterImpl), Health.BindService(healthServiceImpl), ServerReflection.BindService(reflectionImpl) },
                Ports    = { new ServerPort("[::]", options.Port, ServerCredentials.Insecure) }
            };

            server.Start();

            // Mark all services as healthy.
            foreach (var serviceDescriptor in serviceDescriptors)
            {
                healthServiceImpl.SetStatus(serviceDescriptor.FullName, HealthCheckResponse.Types.ServingStatus.Serving);
            }
            // Mark overall server status as healthy.
            healthServiceImpl.SetStatus("", HealthCheckResponse.Types.ServingStatus.Serving);

            Console.WriteLine("Dlink server listening on port " + options.Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
Пример #27
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <HealthService>()
            .As <IHealthService>()
            .SingleInstance();

            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups))
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance();

            builder.RegisterType <RiskConstrainsInitializer>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups));

            builder.RegisterType <OperationValidationRepository>()
            .As <IOperationValidationRepository>()
            .WithParameter(TypedParameter.From(_settings.ConnectionString(x => x.Db.AzureDataConnString)))
            .SingleInstance();

            builder.RegisterType <StatisticsRepository>()
            .As <IStatisticsRepository>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.Db.MongoDataConnString))
            .SingleInstance();

            builder.RegisterType <OperationValidationService>()
            .As <IOperationValidationService>()
            .SingleInstance();

            builder.RegisterType <StatisticsService>()
            .As <IStatisticsService>()
            .SingleInstance();

            builder.RegisterType <OperationRiskEstimator>()
            .As <IOperationRiskEstimator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistry>()
            .As <IRiskConstraintsRegistry>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistryConfigurator>()
            .As <IRiskConstraintsRegistryConfigurator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsFactory>()
            .As <IRiskConstraintsFactory>()
            .SingleInstance();

            builder.RegisterType <BlockchainRiskControlServiceImpl>()
            .AsSelf()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    BlockchainRiskControlService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        BlockchainRiskControlService.BindService(ctx.Resolve <BlockchainRiskControlServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", 5005, ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new TelegramBotClient(string.IsNullOrEmpty(_settings.CurrentValue.Telegram?.Token) ? "1234:test" : _settings.CurrentValue.Telegram?.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
Пример #28
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <Link4PayServiceImpl>()
            .AsSelf()
            .WithParameter("supportedCountries", _appSettings.CurrentValue.Link4PayService.SupportedCountries)
            .WithParameter("supportedCurrencies", _appSettings.CurrentValue.Link4PayService.SupportedCurrencies)
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    Link4PayService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        Link4PayService.BindService(ctx.Resolve <Link4PayServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", _appSettings.CurrentValue.Link4PayService.GrpcPort,
                                       ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new KeyVaultClient(
                    async(string authority, string resource, string scope) =>
            {
                var authContext = new AuthenticationContext(authority);
                var clientCred  =
                    new ClientCredential(_appSettings.CurrentValue.Link4PayService.KeyVault.ClientId, _appSettings.CurrentValue.Link4PayService.KeyVault.ClientSecret);
                var result = await authContext.AcquireTokenAsync(resource, clientCred);
                if (result == null)
                {
                    throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
                }

                return(result.AccessToken);
            }
                    ));

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Link4Pay);
            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.KeyVault);

            builder.RegisterType <EncryptionService>()
            .As <IEncryptionService>()
            .SingleInstance();

            builder.RegisterType <Link4PayApiService>()
            .As <ILink4PayApiService>()
            .SingleInstance();

            builder.RegisterType <AntiFraudChecker>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckPaymentPeriod))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckRegistrationDateSince))
            .WithParameter("notificationEmail", _appSettings.CurrentValue.Link4PayService.AntiFraudNotificationEmail)
            .WithParameter("chatId", _appSettings.CurrentValue.Link4PayService.Telegram.ChatId);

            builder.RegisterType <PaymentOkEmailSender>()
            .As <IPaymentNotifier>()
            .SingleInstance();

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Telegram);

            builder.RegisterInstance(
                string.IsNullOrEmpty(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ? new Mock <ITelegramBotClient>().Object
                : new TelegramBotClient(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
Пример #29
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Factory.StartNew(() =>
            {
                foreach (var serviceGroup in StatefulServices.GroupBy(x => x.Value))
                {
                    switch (serviceGroup.Key)
                    {
                    case EventSourcedStatefulService _:
                        Server.Services.Add(
                            Cloudstate.Eventsourced.EventSourced.BindService(new EntityCollectionService(
                                                                                 LoggerFactory,
                                                                                 Config,
                                                                                 serviceGroup.ToDictionary(
                                                                                     x => x.Key,
                                                                                     x => x.Value as IEventSourcedStatefulService
                                                                                     ),
                                                                                 new Context(new ResolvedServiceCallFactory(StatefulServices))
                                                                                 ))
                            );
                        break;

                    case CrdtStatefulService _:
                        Server.Services.Add(
                            Cloudstate.Crdt.Crdt.BindService(new CrdtEntityCollectionService(
                                                                 LoggerFactory,
                                                                 serviceGroup.ToDictionary(
                                                                     x => x.Key,
                                                                     x => x.Value as ICrdtStatefulService
                                                                     ),
                                                                 new Context(new ResolvedServiceCallFactory(StatefulServices))
                                                                 ))
                            );
                        break;

                    default:
                        throw new NotImplementedException($"Unknown stateful service implementation of {serviceGroup.Key}");
                    }
                }

                Server.Services.Add(
                    EntityDiscovery.BindService(
                        new EntityDiscoveryService(
                            LoggerFactory,
                            StatefulServices
                            )
                        )
                    );

                // TODO: Feature flag this.
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    StatefulServices.Values.Select(x => x.ServiceDescriptor)
                    );
                Server.Services.Add(
                    ServerReflection.BindService(
                        reflectionServiceImpl
                        )
                    );

                Server.Start();
                Logger.LogInformation(
                    $"Server listening on [{Config.Host}:{Config.Port}]"
                    );
            }, cancellationToken);
        }