예제 #1
0
 static async Task Main(string[] args)
 {
     await GrpcServer.Run((context, builder) =>
     {
         builder.RegisterType <DivisionControlService>().As <IGrpcService>();
     });
 }
예제 #2
0
        public async Task ServiceProviderServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <IServiceProviderService>()
            .RegisterService <ISimpleService>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new ServiceProviderServiceImpl(host.ServicePublisher);

                using (var publishScope = host.PublishSingleton <IServiceProviderService>(serviceImpl))
                {
                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceSingleton <IServiceProviderServiceClient>();
                    var serviceRef    = await clientService.GetSimpleServiceAsync();

                    var simpleService = connection.GetServiceInstance(serviceRef);

                    int res = await simpleService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, res);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
예제 #3
0
        public async Task SimpleObjectServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <ISimpleService>();
            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new TestSimpleServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId   = publishScope.Value.ObjectId;
                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <ISimpleService>(objectId);
                    int res           = await clientService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, res);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
예제 #4
0
        public static void Main(string[] args)
        {
            string host = "0.0.0.0";
            int port = 9007;
            var dic = Common.GetArgs(args);
            if (dic != null && dic.Count > 0)
            {
                string tempHost;
                string tempPort;
                if (dic.TryGetValue("host", out tempHost))
                {
                    host = tempHost;
                }
                if (dic.TryGetValue("port", out tempPort))
                {
                    port = Convert.ToInt32(tempPort);
                }
            }

            GrpcServer server = new GrpcServer
            {
                Services = { RPCDemoService.BindService(new RPCDemoImpl()) },
                Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
            };
            Console.WriteLine("Google Grpc Starting");
            foreach (var item in server.Ports)
            {
                Console.WriteLine(string.Format("RPC server {0} listening on port {1}", item.Host, item.Port));
            }
            server.Run();

        }
예제 #5
0
        public async Task Execute(CancellationToken cancellationToken)
        {
            IGrpcConfig grpcConfig = _api.Config <IGrpcConfig>();

            if (grpcConfig.Enabled)
            {
                ILogger    logger     = _api.LogManager.GetClassLogger();
                GrpcServer grpcServer = new GrpcServer(_api.EthereumJsonSerializer, _api.LogManager);
                var        grpcRunner = new GrpcRunner(grpcServer, grpcConfig, _api.LogManager);
                await grpcRunner.Start(cancellationToken).ContinueWith(x =>
                {
                    if (x.IsFaulted && logger.IsError)
                    {
                        logger.Error("Error during GRPC runner start", x.Exception);
                    }
                });

                _api.GrpcServer = grpcServer;

                GrpcPublisher grpcPublisher = new GrpcPublisher(_api.GrpcServer);
                _api.Publishers.Add(grpcPublisher);

                _api.DisposeStack.Push(grpcPublisher);
                _api.DisposeStack.Push(Disposable.Create(() => grpcRunner.StopAsync())); // do not await
            }
        }
예제 #6
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        public void Start()
        {
            GrpcServer.Start();
            var port = GrpcServer.Ports.FirstOrDefault();

            Logger.Info(LoggerMessages.ServerStartedMessage(port.Host, port.Port));
        }
예제 #7
0
        public async Task DeviceServiceTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <IThermostatService>();
            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new ThermostatServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var            objectId   = publishScope.Value.ObjectId;
                    GrpcConnection connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <IThermostatServiceClient>(objectId);
                    var acoId         = clientService.DeviceAcoId;

                    var baseClientService = (IDeviceServiceClient)clientService;
                    var acoId2            = baseClientService.DeviceAcoId;
                    Assert.AreEqual(acoId, acoId2);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
예제 #8
0
        public async Task EventHandlersTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <ISimpleServiceWithEvents>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());
            host.Start();

            try
            {
                var serviceImpl = new TestServiceWithEventsImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId = publishScope.Value.ObjectId;

                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <ISimpleServiceWithEvents>(objectId);

                    TaskCompletionSource <ValueChangedEventArgs> detailedTcs     = new TaskCompletionSource <ValueChangedEventArgs>();
                    EventHandler <ValueChangedEventArgs>         detailedHandler = (s, e) =>
                    {
                        detailedTcs.SetResult(e);
                    };

                    clientService.DetailedValueChanged += detailedHandler;

                    await((IRpcProxy)clientService).WaitForPendingEventHandlersAsync();

                    clientService.SetValueAsync(12).Forget();

                    var completedTask = await Task.WhenAny(detailedTcs.Task, Task.Delay(1000));

                    Assert.AreEqual(detailedTcs.Task, completedTask);
                    Assert.IsTrue(completedTask.IsCompletedSuccessfully());

                    var detailedArgs = detailedTcs.Task.Result;

                    clientService.DetailedValueChanged -= detailedHandler;
                    await((IRpcProxy)clientService).WaitForPendingEventHandlersAsync();
                    clientService.SetValueAsync(13).Forget();

                    await Task.Delay(200);

                    Assert.IsFalse(serviceImpl.HasDetailedValueChangedHandler);
                    Assert.IsFalse(serviceImpl.HasValueChangedHandler);

                    Assert.AreEqual(12, detailedArgs.NewValue);
                    Assert.AreEqual(0, detailedArgs.OldValue);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
예제 #9
0
        public void Start()
        {
            ServerStarted = true;
            GrpcServer.Start();

            // Can't log before the job manager starts (Master Interpreter looks for the first newline to decide when it's safe to send commands)
            //Console.WriteLine("Listening for progress feedback on address {0}", ServerAddress);
        }
예제 #10
0
        public void Dispose()
        {
            CloseServerAction.Invoke();
            GrpcServer.ShutdownAsync().Wait();
            var port = GrpcServer.Ports.FirstOrDefault();

            Logger.Info(message: LoggerMessages.ServerClosedMessage(port.Host, port.Port));
        }
예제 #11
0
 /// <summary>
 /// Initializes new instance of <see cref="GrpcHostedService"/>
 /// </summary>
 /// <param name="server">Instance of <see cref="Server"/>.</param>
 /// <param name="clientCache" Instance of <see cref="IGrpcClientCache"/>.
 /// <param name="definitions">Dictionary that should contain gRPC service implementation that need to be registered with server.</param>
 /// <param name="applicationLifetime">Instance of <see cref="IApplicationLifetime"/>.</param>
 /// <param name="logger">Instance of <see cref="ILogger"/> that will be configured to use Serilog Splunk or Console sink.</param>
 public GrpcHostedService(
     IApplicationLifetime applicationLifetime,
     GrpcServer server,
     Microsoft.Extensions.Logging.ILogger logger)
 {
     _applicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
     _server = server ?? throw new ArgumentNullException(nameof(server));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
예제 #12
0
        /// <summary>
        /// 启动服务
        /// </summary>
        public void Start()
        {
            GrpcServer server = new GrpcServer(_config.LocalAddress.Split(':')[0], int.Parse(_config.LocalAddress.Split(':')[1]), _config.ClusterToken, new DebugConsole());

            server.Register(typeof(IHost), typeof(Host), _host);
            server.Start().Wait();

            DebugConsole.WriteLine("Raft is Running...");
            DebugConsole.WriteLine($"NodeId:{_config.NodeId} name:{_config.NodeName} address:{_config.LocalAddress}...");
        }
예제 #13
0
        public static void TestFixtureSetup()
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;

            // collects gRpc traces for tests https://github.com/grpc/grpc/blob/master/TROUBLESHOOTING.md
            System.Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            System.Environment.SetEnvironmentVariable("GRPC_TRACE", "all");

            GrpcServer = UnitTestsHelper.StartGrpcServer(Port, true);
        }
예제 #14
0
 private static void CreateServer()
 {
     _grpcServer = new GrpcServer(_service, _auth);
     _server     = new Grpc.Core.Server
     {
         Services = { TriathlonService.BindService(_grpcServer) },
         Ports    = { new ServerPort(GetConfig("serverHost",     "localhost"),
                                     GetIntegerConfig("serverPort",        8000),
                                     ServerCredentials.Insecure) }
     };
 }
예제 #15
0
 private static async Task Main(string[] args)
 {
     Console.Title = "gRPC Service";
     GrpcServer.Start();
     Console.WriteLine("gRPC server started.\nPress spacebar to notify item changes or any other key to stop it.");
     while (Console.ReadKey().Key == ConsoleKey.Spacebar)
     {
         RaiseItemsChanged();
     }
     await GrpcServer.Stop();
 }
예제 #16
0
        public static async Task Main(string[] args)
        {
            // This example shows how to explicitly setup a gRPC RPC server and a Pipelines RPC server
            // with a common service publisher.
            //
            // In a real scenario, it is probably more suitable to use the .NET generic host
            // (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host).
            //
            // The NetGrpcServer example shows what a host setup could look like.


            Console.WriteLine("Initializing gRPC server and pipelines server.");
            var serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var definitionsBuilder = new RpcServiceDefinitionBuilder();
            var rpcPublisher       = new RpcServicePublisher(definitionsBuilder);

            RegisterServiceDefinitions(definitionsBuilder);
            PublishServices(rpcPublisher);

            var serializer = new ProtobufSerializer();

            var grpcServer = new GrpcServer(rpcPublisher, serviceProvider, serializer);

            grpcServer.AllowAutoPublish = true;
            grpcServer.AddEndPoint(CreateGrpcEndPoint(50051));

            var pipelinesServer = new RpcPipelinesServer(rpcPublisher, serviceProvider, serializer);

            pipelinesServer.AllowAutoPublish = true;
            pipelinesServer.AddEndPoint(new TcpPipelinesEndPoint("127.0.0.1", 50052, false));

            Console.WriteLine("Starting gRPC server and pipelines server.");

            // Once the gRPC server is started, it is no longer possible to register service definitions.
            grpcServer.Start();
            pipelinesServer.Start();

            Console.WriteLine("gRPC server and pipelines server are running, press any key to shutdown.");

            Console.ReadKey();

            Console.WriteLine("Shutting down servers.");

            await Task.WhenAll(grpcServer.ShutdownAsync(), pipelinesServer.ShutdownAsync());

            Console.WriteLine("Ended");
        }
예제 #17
0
        public async Task BlockingServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder
            .RegisterService <IBlockingService>()
            .RegisterService <ISimpleService>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();

            try
            {
                var serviceImpl = new TestBlockingSimpleServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId = publishScope.Value.ObjectId;

                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <IBlockingServiceClient>(objectId);

                    int blockingRes = clientService.Add(12, 13);
                    Assert.AreEqual(12 + 13, blockingRes);

                    int asyncRes = await clientService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, asyncRes);

                    clientService.Value = 123.45;
                    Assert.AreEqual(123.45, await clientService.GetValueAsync());

                    await clientService.SetValueAsync(543.21);

                    Assert.AreEqual(543.21, clientService.Value);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
예제 #18
0
        private async Task InitializeWorkersAsync()
        {
            var serverImpl = new FunctionRpcService(EventManager, _logger);
            var server     = new GrpcServer(serverImpl, ScriptOptions.MaxMessageLengthBytes);

            using (_metricsLogger.LatencyEvent(MetricEventNames.HostStartupGrpcServerLatency))
            {
                await server.StartAsync();
            }

            var processFactory = new DefaultWorkerProcessFactory();

            try
            {
                _processRegistry = ProcessRegistryFactory.Create();
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Unable to create process registry");
            }

            CreateChannel channelFactory = (languageWorkerConfig, registrations, attemptCount) =>
            {
                return(new LanguageWorkerChannel(
                           ScriptOptions,
                           EventManager,
                           processFactory,
                           _processRegistry,
                           registrations,
                           languageWorkerConfig,
                           server.Uri,
                           _loggerFactory, // TODO: DI (FACAVAL) Pass appropriate logger. Channel facory should likely be a service.
                           _metricsLogger,
                           attemptCount));
            };

            _functionDispatcher = new FunctionDispatcher(EventManager, server, channelFactory, _workerConfigs, _language);

            _eventSubscriptions.Add(EventManager.OfType <WorkerProcessErrorEvent>()
                                    .Subscribe(evt =>
            {
                HandleHostError(evt.Exception);
            }));
        }
예제 #19
0
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.CurrentDirectory);
            var options = new GrpcServerOptions()
            {
                Host           = "127.0.0.1",
                Port           = 3002,
                NamespaceName  = "Atlantis.Simple",
                PackageName    = "Atlantis.Simple",
                ServiceName    = "AtlantisService",
                ScanAssemblies = new string[]
                {
                    typeof(IPersonServicer).Assembly.FullName
                }
            };

            var consulSetting = new ConsulSettingOptions()
            {
                ConsulAddressUrl = "http://192.168.0.251:8500"
            };
            var serviceOptions = new ConsulServiceOptions()
            {
                ServiceName = "Atlantis.Test",
                Address     = "127.0.0.1",
                Port        = 3002,
                TTL         = 1000
            };

            var consulManager = new ConsulManager()
                                .Init(consulSetting)
                                .WithServiceOptions(serviceOptions);

            consulManager.Service.RegisteAsync().Wait();

            //GrpcConfiguration.LoggerFactory=new Loggerfac();

            var server = new GrpcServer(options);

            ObjectContainer.Register <IPersonServicer, PersonServicer>(LifeScope.Single);
            server.Start();

            Console.WriteLine("Server is running...");
            Console.ReadLine();
        }
예제 #20
0
        /// <inheritdoc />
        public void Start()
        {
            try
            {
                ChannelOption optionReceive = new ChannelOption(ChannelOptions.MaxReceiveMessageLength, GrpcStream.MaxPackageSize);
                ChannelOption optionSend    = new ChannelOption(ChannelOptions.MaxSendMessageLength, GrpcStream.MaxPackageSize);

                if (System.IO.File.Exists("ca.crt"))
                {
                    var cacert         = System.IO.File.ReadAllText(@"ca.crt");
                    var servercert     = System.IO.File.ReadAllText(@"server.crt");
                    var serverkey      = System.IO.File.ReadAllText(@"server.key");
                    var keypair        = new KeyCertificatePair(servercert, serverkey);
                    var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
                    {
                        keypair
                    }, cacert, false);

                    this.grpcServer = new Server
                    {
                        Services = { GrpcServer.BindService(this) },
                        Ports    = { new ServerPort(this.Host.Address.ToString(), this.Host.Port, sslCredentials) }
                    };
                }
                else
                {
                    this.grpcServer = new Server(new List <ChannelOption>()
                    {
                        optionReceive, optionSend
                    })
                    {
                        Services = { GrpcServer.BindService(this) },
                        Ports    = { new ServerPort(this.Host.Address.ToString(), this.Host.Port, ServerCredentials.Insecure) }
                    };
                }
                this.grpcServer.Start();

                this.Log(this.ToString(), "GRPC-Server server listening on port " + this.Host.Port, LogLevel.Info);
            }
            catch (Exception ex)
            {
                throw new Exception("Grpc server error", ex);
            }
        }
예제 #21
0
        internal static GrpcServer StartGrpcServer(int port, bool isRetryEnabled)
        {
            // max 3 times attemps, including the original request.
            RetryPolicy retryPolicy = isRetryEnabled ?
                                      new RetryPolicy(3, (float)0.1, 5, 2) :
                                      null;

            GrpcServerLegacyQueryHandlerBase mockLegacyQueryHandler = new RetryableLegacyQueryHandler();
            //GrpcServerLegacyQueryHandlerBase mockLegacyQueryHandler =
            //                                    isRetryEnabled ?
            //                                        (GrpcServerLegacyQueryHandlerBase)new MockRetryableLegacyQueryHandler() :
            //                                        (GrpcServerLegacyQueryHandlerBase)new MockLegacyQueryHandler();
            LegacyQueryService legacyQueryService = GrpcServer.CreateLegacyQueryService(mockLegacyQueryHandler);

            GrpcServer grpcServer = new GrpcServer(
                port, legacyQueryService, retryPolicy: retryPolicy);

            grpcServer.Start();

            return(grpcServer);
        }
예제 #22
0
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            TripRepository    tripRepository    = new TripRepository();
            TripValidator     tripValidator     = new TripValidator();
            AccountRepository accountRepository = new AccountRepository();
            AccountValidator  accountValidator  = new AccountValidator();
            BookingRepository bookingRepository = new BookingRepository();
            BookingValidator  bookingValidator  = new BookingValidator();
            ITripServices     tripServices      = new TripServicesImpl(accountRepository, tripRepository, bookingRepository,
                                                                       accountValidator, tripValidator, bookingValidator);

            TripServicesGrpcImpl tripServicesGrpc = new TripServicesGrpcImpl(tripServices);
            GrpcServer           server           = new GrpcServer(int.Parse(ConfigurationManager.AppSettings["port"]),
                                                                   ConfigurationManager.AppSettings["host"], tripServicesGrpc);

            server.Start();
        }
예제 #23
0
        /// <summary>
        /// </summary>
        static void Init()
        {
            Console.WriteLine($"Init() called on thread {Thread.CurrentThread.ManagedThreadId}");

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
            {
                RemoteCertificateValidationCallback =
                    (sender, certificate, chain, sslPolicyErrors) => true
            };

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            var mcTask = ModuleClient.CreateFromEnvironmentAsync(settings);

            mcTask.Wait();
            s_moduleClient = mcTask.Result;
            s_moduleClient.OpenAsync().Wait();

            // Get module twin for initial settings
            Task <Twin> twinTask = s_moduleClient.GetTwinAsync();

            twinTask.Wait();
            Twin twin = twinTask.Result;

            OnDesiredPropertiesUpdate(twin.Properties.Desired, s_moduleClient).Wait();
            s_moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            s_grpcServer = new GrpcServer("VideoProcessorModule", OnImageReceived);
            Console.WriteLine("Starting gRPC server");
            s_grpcServer.Start();

            Task processingTask = new Task(ProcessingLoop);

            processingTask.Start();

            Console.WriteLine("IoT Hub module client initialized.");
        }
예제 #24
0
        public override void Start()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
            GrpcEnvironment.SetLogger(new UnityLogger());

            Converter?.SetInitTRS(Vector3.zero, Quaternion.identity);

            var servicesChain = new IChainable <MapsManagerPb.MapsManagerPbBase>[]
            {
                new PointsMapManager(_containerTree.Points, Converter),
                new ObservationsMapManager(_containerTree.Observations, Converter),
                new TrackedObjsMapManager(_containerTree.TrackedObjs, Converter),
                new LinesMapManager(_containerTree.Lines, Converter),
                new InfinitePlanesMapManager(_containerTree.InfinitePlanes, Converter)
            }.BuildChain();

            _containerTree.DisplayName = $"From gRPC at port {TypedSettings.Port}";
#if UNITY_EDITOR || UNITY_STANDALONE
            Debug.Log($"{TypedSettings.IPAddress}:{TypedSettings.Port}");
#endif

            _server = new GrpcServer()
            {
                Services =
                {
                    MapsManagerPb.BindService(servicesChain),
                    SceneManagerPb.BindService(new SceneManager(_containerTree)),
                    ImageManagerPb.BindService(new ImageManager((RawImagePresenter)_containerTree.Image))
                },
                Ports =
                {
                    new ServerPort("0.0.0.0", TypedSettings.Port, ServerCredentials.Insecure),
                },
            };
            StartServer();
        }
        /// <summary>
        /// TODO: Use factories instead of using this.connnectionType.
        /// </summary>
        /// <param name="serviceDefinitionsProvider"></param>
        /// <param name="proxyDefinitionsProvider"></param>
        /// <returns></returns>
        protected (IRpcServerHost, IRpcChannel) CreateServerAndConnection(
            IRpcServiceDefinitionsProvider serviceDefinitionsProvider = null,
            Action <RpcServerOptions> configServerOptions             = null,
            Action <RpcClientOptions> configClientOptions             = null,
            Action <IServiceCollection> configureServices             = null)
        {
            var rpcServerId = RpcServerId.NewId();

            var serverOptions = new RpcServerOptions {
                Serializer = this.serializer
            };
            var clientOptions = new RpcClientOptions {
                Serializer = this.serializer
            };

            configServerOptions?.Invoke(serverOptions);
            configClientOptions?.Invoke(clientOptions);

            IServiceProvider services = GetServiceProvider(configureServices);

            switch (this.ConnectionType)
            {
            case RpcConnectionType.LightweightTcp:
            case RpcConnectionType.LightweightSslTcp:
            {
                var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions,
                                                    loggerFactory: services.GetService <ILoggerFactory>());

                SslServerOptions sslServerOptions = null;
                if (this.ConnectionType == RpcConnectionType.LightweightSslTcp)
                {
                    sslServerOptions = new SslServerOptions(new X509Certificate2(TestCertificates.ServerPFXPath, "1111"));
                }

                host.AddEndPoint(new TcpRpcEndPoint("127.0.0.1", TcpTestPort, false, sslServerOptions));

                SslClientOptions sslClientOptions = null;
                if (this.ConnectionType == RpcConnectionType.LightweightSslTcp)
                {
                    sslClientOptions = new SslClientOptions {
                        RemoteCertificateValidationCallback = this.ValidateTestCertificate
                    };
                }
                var connection = new TcpRpcConnection(
                    new RpcConnectionInfo("TCP", new Uri($"lightweight.tcp://127.0.0.1:{TcpTestPort}"), rpcServerId),
                    sslClientOptions,
                    clientOptions.AsImmutable(),
                    this.LightweightOptions);

                return(host, connection);
            }

            case RpcConnectionType.LightweightNamedPipe:
            {
                var server = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions,
                                                      loggerFactory: services.GetService <ILoggerFactory>());
                server.AddEndPoint(new NamedPipeRpcEndPoint("testpipe"));

                var connection = new NamedPipeRpcConnection(
                    new RpcConnectionInfo(new Uri("lightweight.pipe://./testpipe")),
                    clientOptions.AsImmutable(),
                    this.LightweightOptions);

                return(server, connection);
            }

            case RpcConnectionType.LightweightInproc:
            {
                Pipe requestPipe  = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool));
                Pipe responsePipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.Inline));

                var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions,
                                                    loggerFactory: services.GetService <ILoggerFactory>());
                host.AddEndPoint(new InprocRpcEndPoint(new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer)));

                var connection = new InprocRpcConnection(new RpcConnectionInfo("Direct", new Uri("direct:localhost"), rpcServerId),
                                                         new DirectDuplexPipe(responsePipe.Reader, requestPipe.Writer), clientOptions.AsImmutable());
                return(host, connection);
            }

            case RpcConnectionType.Grpc:
            {
                var host = new GrpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions);
                host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint());

                var connection = new GrpcConnection(
                    new RpcConnectionInfo("TCP", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId),
                    TestCertificates.GrpcSslCredentials, clientOptions.AsImmutable());
                return(host, connection);
            }

#if PLAT_NET_GRPC
            case RpcConnectionType.NetGrpc:
            {
                var server = CreateNetGrpcServer(serviceDefinitionsProvider, rpcServerId, serverOptions, configureServices);
                //var host = new GrpcServer(rpcServerId, serviceDefinitionsBuilder, null, options);
                //host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint());

                var handler = new System.Net.Http.HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) =>
                {
                    return(true);
                };
                var channelOptions = new GrpcNet.Client.GrpcChannelOptions()
                {
                    HttpClient        = new System.Net.Http.HttpClient(handler),
                    DisposeHttpClient = true
                };


                var connection = new NetGrpcConnection(
                    new RpcConnectionInfo("net-grpc", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId),
                    clientOptions.AsImmutable(), channelOptions);
                return(server, connection);
            }
#endif
            }

            throw new NotSupportedException();
        }
예제 #26
0
 static void Main(string[] args)
 {
     var server = new GrpcServer();
 }
예제 #27
0
        protected async Task StartRunners(IConfigProvider configProvider)
        {
            IInitConfig        initConfig        = configProvider.GetConfig <IInitConfig>();
            IJsonRpcConfig     jsonRpcConfig     = configProvider.GetConfig <IJsonRpcConfig>();
            IMetricsConfig     metricsConfig     = configProvider.GetConfig <IMetricsConfig>();
            NLogManager        logManager        = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory);
            IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled
                ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager)
                : (IRpcModuleProvider)NullModuleProvider.Instance;
            EthereumJsonSerializer jsonSerializer    = new EthereumJsonSerializer();
            WebSocketsManager      webSocketsManager = new WebSocketsManager();

            if (!string.IsNullOrEmpty(metricsConfig.NodeName))
            {
                logManager.SetGlobalVariable("nodeName", metricsConfig.NodeName);
            }

            if (metricsConfig.Enabled)
            {
                Metrics.Version = VersionToMetrics.ConvertToNumber(ClientVersion.Version);
                MetricsUpdater metricsUpdater = new MetricsUpdater(metricsConfig);
                _monitoringService = new MonitoringService(metricsUpdater, metricsConfig, logManager);
                _monitoringService.RegisterMetrics(typeof(Nethermind.Blockchain.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Db.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Evm.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.JsonRpc.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Trie.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Network.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Synchronization.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.TxPool.Metrics));
                _monitoringService.RegisterMetrics(typeof(Metrics));

                await _monitoringService.StartAsync().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during starting a monitoring.", x.Exception);
                    }
                });
            }
            else
            {
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info("Grafana / Prometheus metrics are disabled in configuration");
                }
            }

            IGrpcConfig grpcConfig = configProvider.GetConfig <IGrpcConfig>();
            GrpcServer? grpcServer = null;

            if (grpcConfig.Enabled)
            {
                grpcServer  = new GrpcServer(jsonSerializer, logManager);
                _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager);
                await _grpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during GRPC runner start", x.Exception);
                    }
                });
            }

            INdmDataPublisher?         ndmDataPublisher          = null;
            INdmConsumerChannelManager?ndmConsumerChannelManager = null;
            INdmInitializer?           ndmInitializer            = null;
            INdmConfig ndmConfig  = configProvider.GetConfig <INdmConfig>();
            bool       ndmEnabled = ndmConfig.Enabled;

            if (ndmEnabled)
            {
                ndmDataPublisher          = new NdmDataPublisher();
                ndmConsumerChannelManager = new NdmConsumerChannelManager();
                string initializerName = ndmConfig.InitializerName;
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info($"NDM initializer: {initializerName}");
                }
                Type ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies()
                                          .SelectMany(a => a.GetTypes())
                                          .FirstOrDefault(t =>
                                                          t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName);
                NdmModule          ndmModule          = new NdmModule();
                NdmConsumersModule ndmConsumersModule = new NdmConsumersModule();
                ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule, logManager).CreateOrFail();

                if (grpcServer != null)
                {
                    ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer));
                }

                webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher, jsonSerializer));
            }

            _ethereumRunner = new EthereumRunner(
                rpcModuleProvider,
                configProvider,
                logManager,
                grpcServer,
                ndmConsumerChannelManager,
                ndmDataPublisher,
                ndmInitializer,
                webSocketsManager,
                jsonSerializer,
                _monitoringService);

            await _ethereumRunner.Start().ContinueWith(x =>
            {
                if (x.IsFaulted && (_logger?.IsError ?? false))
                {
                    _logger !.Error("Error during ethereum runner start", x.Exception);
                }
            });

            if (jsonRpcConfig.Enabled)
            {
                rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager), true));
                JsonRpcService   jsonRpcService   = new JsonRpcService(rpcModuleProvider, logManager);
                JsonRpcProcessor jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, jsonRpcConfig, new FileSystem(), logManager);
                if (initConfig.WebSocketsEnabled)
                {
                    webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer), true);
                }

                Bootstrap.Instance.JsonRpcService = jsonRpcService;
                Bootstrap.Instance.LogManager     = logManager;
                Bootstrap.Instance.JsonSerializer = jsonSerializer;
                _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager);
                await _jsonRpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during jsonRpc runner start", x.Exception);
                    }
                });
            }
            else
            {
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info("Json RPC is disabled");
                }
            }
        }
예제 #28
0
 public void Stop()
 {
     GrpcServer.ShutdownAsync().Wait();
     ServerStarted = false;
 }
예제 #29
0
        protected async Task StartRunners(IConfigProvider configProvider)
        {
            IInitConfig        initConfig        = configProvider.GetConfig <IInitConfig>();
            IJsonRpcConfig     jsonRpcConfig     = configProvider.GetConfig <IJsonRpcConfig>();
            var                metricsParams     = configProvider.GetConfig <IMetricsConfig>();
            var                logManager        = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory);
            IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled
                ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager)
                : (IRpcModuleProvider)NullModuleProvider.Instance;
            var jsonSerializer    = new EthereumJsonSerializer();
            var webSocketsManager = new WebSocketsManager();

            INdmDataPublisher          ndmDataPublisher          = null;
            INdmConsumerChannelManager ndmConsumerChannelManager = null;
            INdmInitializer            ndmInitializer            = null;
            var ndmConfig  = configProvider.GetConfig <INdmConfig>();
            var ndmEnabled = ndmConfig.Enabled;

            if (ndmEnabled)
            {
                ndmDataPublisher          = new NdmDataPublisher();
                ndmConsumerChannelManager = new NdmConsumerChannelManager();
                var initializerName = ndmConfig.InitializerName;
                if (Logger.IsInfo)
                {
                    Logger.Info($"NDM initializer: {initializerName}");
                }
                var ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies()
                                         .SelectMany(a => a.GetTypes())
                                         .FirstOrDefault(t =>
                                                         t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName);
                var ndmModule          = new NdmModule();
                var ndmConsumersModule = new NdmConsumersModule();
                ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule,
                                                           logManager).CreateOrFail();
            }

            var        grpcConfig = configProvider.GetConfig <IGrpcConfig>();
            GrpcServer grpcServer = null;

            if (grpcConfig.Enabled)
            {
                grpcServer = new GrpcServer(jsonSerializer, logManager);
                if (ndmEnabled)
                {
                    ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer));
                }

                _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager);
                await _grpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during GRPC runner start", x.Exception);
                    }
                });
            }

            if (initConfig.WebSocketsEnabled)
            {
                if (ndmEnabled)
                {
                    webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher,
                                                                        jsonSerializer));
                }
            }

            _ethereumRunner = new EthereumRunner(rpcModuleProvider, configProvider, logManager, grpcServer,
                                                 ndmConsumerChannelManager, ndmDataPublisher, ndmInitializer, webSocketsManager, jsonSerializer);
            await _ethereumRunner.Start().ContinueWith(x =>
            {
                if (x.IsFaulted && Logger.IsError)
                {
                    Logger.Error("Error during ethereum runner start", x.Exception);
                }
            });

            if (jsonRpcConfig.Enabled)
            {
                rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager)));
                var jsonRpcService   = new JsonRpcService(rpcModuleProvider, logManager);
                var jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, logManager);
                if (initConfig.WebSocketsEnabled)
                {
                    webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer));
                }

                Bootstrap.Instance.JsonRpcService = jsonRpcService;
                Bootstrap.Instance.LogManager     = logManager;
                Bootstrap.Instance.JsonSerializer = jsonSerializer;
                _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor,
                                                   webSocketsManager);
                await _jsonRpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during jsonRpc runner start", x.Exception);
                    }
                });
            }
            else
            {
                if (Logger.IsInfo)
                {
                    Logger.Info("Json RPC is disabled");
                }
            }

            if (metricsParams.Enabled)
            {
                var intervalSeconds = metricsParams.IntervalSeconds;
                _monitoringService = new MonitoringService(new MetricsUpdater(intervalSeconds),
                                                           metricsParams.PushGatewayUrl, ClientVersion.Description,
                                                           metricsParams.NodeName, intervalSeconds, logManager);
                await _monitoringService.StartAsync().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during starting a monitoring.", x.Exception);
                    }
                });
            }
            else
            {
                if (Logger.IsInfo)
                {
                    Logger.Info("Monitoring is disabled");
                }
            }
        }
예제 #30
0
 public GrpcServerHostedService(GrpcServer grpcServer,
                                ILogger <GrpcServerHostedService> logger)
 {
     _grpcServer = grpcServer ?? throw new ArgumentNullException(nameof(grpcServer));
     _logger     = logger ?? throw new ArgumentNullException(nameof(logger));
 }