public async Task UnserializableOutput_ThrowFaultException(string pipeName)
        {
            _serviceMock
            .Setup(x => x.UnserializableOutput())
            .Returns(UnserializableObject.Create());

            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(pipeName);
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, pipeName);
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            IpcFaultException exception = await Assert.ThrowsAnyAsync <IpcFaultException>(async() =>
            {
                await client.InvokeAsync(x => x.UnserializableOutput());
            });

            Assert.Equal(IpcStatus.InternalServerError, exception.Status);
#endif

            IpcFaultException exception2 = await Assert.ThrowsAnyAsync <IpcFaultException>(async() =>
            {
                var request = TestHelpers.CreateIpcRequest("UnserializableOutput");
                await client.InvokeAsync(request);
            });

            Assert.Equal(IpcStatus.InternalServerError, exception2.Status);
        }
Exemple #2
0
        public void ConnectionCancelled_Throw()
        {
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddTcpIpcClient <ITestService>(name, (_, options) =>
                {
                    // Connect to a non-routable IP address can trigger timeout
                    options.ServerIp = IPAddress.Parse("10.0.0.0");
                });
            });

            using (var cts = new CancellationTokenSource())
            {
                Task.WaitAll(
                    Task.Run(async() =>
                {
                    await Assert.ThrowsAsync <OperationCanceledException>(async() =>
                    {
                        var request = TestHelpers.CreateIpcRequest(typeof(ITestService), "StringType", new object[] { string.Empty });
                        await client.InvokeAsync(request, cts.Token);
                    });
                }),
                    Task.Run(() => cts.CancelAfter(1000)));
            }
        }
        public async Task ServerIsOff_Timeout()
        {
            int timeout = 1000; // 1s
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName          = "inexisted-pipe";
                    options.ConnectionTimeout = timeout;
                });
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            var sw = Stopwatch.StartNew();
            await Assert.ThrowsAsync <TimeoutException>(async() =>
            {
                string output = await client.InvokeAsync(x => x.StringType("abc"));
            });

            Assert.True(sw.ElapsedMilliseconds < timeout * 2); // makesure timeout works with marge
#endif

            var sw2 = Stopwatch.StartNew();
            await Assert.ThrowsAsync <TimeoutException>(async() =>
            {
                var request   = TestHelpers.CreateIpcRequest(typeof(ITestService), "StringType", false, new object[] { "abc" });
                string output = await client.InvokeAsync <string>(request);
            });

            Assert.True(sw2.ElapsedMilliseconds < timeout * 2); // makesure timeout works with marge
        }
        public async Task UnserializableInput_ThrowSerializationException(string pipeName)
        {
            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(pipeName);
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, pipeName);
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            await Assert.ThrowsAnyAsync <IpcSerializationException>(async() =>
            {
                await client.InvokeAsync(x => x.UnserializableInput(UnserializableObject.Create()));
            });
#endif

            await Assert.ThrowsAnyAsync <IpcSerializationException>(async() =>
            {
                var request = TestHelpers.CreateIpcRequest(typeof(ITestService), "UnserializableInput", UnserializableObject.Create());
                await client.InvokeAsync(request);
            });
        }
        internal void CleanupServer()
        {
            try
            {
                _queueProcessMonitor.Shutdown();
                _hangfireServerMonitor.Shutdown();
                if (_startWebServer != null)
                {
                    _startWebServer.Dispose();
                    _startWebServer = null;
                }

                if (_ipcClient != null)
                {
                    _ipcClient.Dispose();
                    _ipcClient = null;
                }

                DebugDispatcher.Instance.Shutdown();
            }
            catch (Exception ex)
            {
                Dev2Logger.Error("Dev2.ServerLifecycleManager", ex, GlobalConstants.WarewolfError);
            }
        }
Exemple #6
0
        public async Task Exception_ThrowWithDetails(string pipeName, string details)
        {
            _serviceMock.Setup(x => x.ThrowException())
            .Throws(new Exception(details));

            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(options =>
                {
                    options.PipeName = pipeName;
                    options.IncludeFailureDetailsInResponse = true;
                });
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName = pipeName;
                });
            });

            IpcFaultException actual = await Assert.ThrowsAsync <IpcFaultException>(async() =>
            {
                await client.InvokeAsync(x => x.ThrowException());
            });

            Assert.NotNull(actual.InnerException);
            Assert.NotNull(actual.InnerException.InnerException);
            Assert.Equal(details, actual.InnerException.InnerException.Message);
        }
Exemple #7
0
        private async void SendTask(WebSocketContext context, IIpcClient client, CancellationToken cancellationToken)
        {
            try
            {
                var webSocket = context.WebSocket;
                while (!cancellationToken.IsCancellationRequested && webSocket.State == WebSocketState.Open)
                {
                    var result = await client.SendChannel.Reader.ReadAsync(cancellationToken);

                    if (webSocket.State != WebSocketState.Open)
                    {
                        break;
                    }

                    Logger.Debug("\"{0}\" sent data: \"{1}\"", client.IpcName, result);
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        continue;
                    }

                    await SendStringAsync(webSocket, result, cancellationToken);
                }
            }
            catch (OperationCanceledException) { }
        }
Exemple #8
0
        public ServerLifecycleManager(StartupConfiguration startupConfiguration)
        {
            SetApplicationDirectory();
            _writer = startupConfiguration.Writer;
            _serverEnvironmentPreparer     = startupConfiguration.ServerEnvironmentPreparer;
            _startUpDirectory              = startupConfiguration.Directory;
            _startupResourceCatalogFactory = startupConfiguration.ResourceCatalogFactory;
            _ipcClient      = startupConfiguration.IpcClient;
            _assemblyLoader = startupConfiguration.AssemblyLoader;
            _pulseLogger    = new PulseLogger(60000).Start();
            _pulseTracker   = new PulseTracker(TimeSpan.FromDays(1).TotalMilliseconds).Start();
            _serverEnvironmentPreparer.PrepareEnvironment();
            _startWebServer         = startupConfiguration.StartWebServer;
            _webServerConfiguration = startupConfiguration.WebServerConfiguration;

            _loggingProcessMonitor = startupConfiguration.LoggingServiceMonitor;
            _loggingProcessMonitor.OnProcessDied += (e) => _writer.WriteLine("logging service exited");

            _queueProcessMonitor = startupConfiguration.QueueWorkerMonitor;
            _queueProcessMonitor.OnProcessDied += (config) => _writer.WriteLine($"queue process died: {config.Name}({config.Id})");

            _webSocketPool = startupConfiguration.WebSocketPool;

            SecurityIdentityFactory.Set(startupConfiguration.SecurityIdentityFactory);
        }
Exemple #9
0
        public async Task StreamTranslator_HappyPath(string pipeName, string input, string expected)
        {
            _serviceMock
            .Setup(x => x.StringType(input))
            .Returns(expected);

            IIpcClient <ITestService> client = _factory
                                               .WithServiceImplementation(_ => _serviceMock.Object)
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(options =>
                {
                    options.PipeName         = pipeName;
                    options.StreamTranslator = x => new XorStream(x);
                });
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName         = pipeName;
                    options.StreamTranslator = x => new XorStream(x);
                });
            });

            string actual = await client.InvokeAsync(x => x.StringType(input));

            Assert.Equal(expected, actual);
        }
Exemple #10
0
        public void Dispose()
        {
            Log.Output -= HandleMessage;
            Server      = null;

            Log.Debug("Daemon", $"Stopped log server {{{Identifier}}}");
        }
Exemple #11
0
        private void OnStartup(object sender, StartupEventArgs eventArgs)
        {
            _ipcClient = CreateGrpcClient();
            _ipcClient.Start();

            var acquisitionManagerProxy = CreateGrpcAcquisitionManagerProxy(_ipcClient);

            ServiceLocator.Instance.RegisterService <IAcquisitionManager>(acquisitionManagerProxy);
        }
Exemple #12
0
 /// <summary>
 /// Creates a new Anperi interface. It will connect to the IPC server automatically. To actually use this class you'll need to subscribe to almost all events.
 /// </summary>
 public Anperi()
 {
     _ipcClient                  = new NamedPipeIpcClient();
     _ipcClient.Opened          += _ipcClient_Opened;
     _ipcClient.MessageReceived += _ipcClient_MessageReceived;
     _ipcClient.Closed          += _ipcClient_Closed;
     _ipcClient.Error           += _ipcClient_Error;
     ReconnectIn(TimeSpan.Zero);
 }
Exemple #13
0
        private IAcquisitionManager CreateGrpcAcquisitionManagerProxy(IIpcClient ipcClient)
        {
            var grpcClientImplementation = (IpcClientGrpcImplementation)ipcClient;

            var grpcAcquisitionManagerProxyImplementation = new AcquisitionManagerProxyGrpcImplementation(
                grpcClientImplementation.Channel,
                grpcClientImplementation.CancellationToken);

            return(grpcAcquisitionManagerProxyImplementation);
        }
        public async Task Run()
        {
            _thread = new Thread(MetricsSendingLoop);
            _thread.Start();

            var periodMs = int.Parse(_config.ConfigItems[Constants.Config_MetricMeasurmantPeriod]);

            _client = IpcConnector.Connect(_config);
            _timer  = new Timer(OnTimerTick, null, periodMs, periodMs);

            await MetricsMeasurmentLoop();
        }
Exemple #15
0
        public ContractTest(IpcApplicationFactory <ITestService> factory)
        {
            string pipeName = Guid.NewGuid().ToString();

            _client = factory
                      .WithServiceImplementation(_ => _serviceMock.Object)
                      .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(pipeName);
            })
                      .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, pipeName);
            });
        }
        public HappyPathTest(IpcApplicationFactory <ITestService> factory)
        {
            int port = _rand.Next(10000, 50000);

            _client = factory
                      .WithServiceImplementation(_ => _serviceMock.Object)
                      .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddTcpEndpoint <ITestService>(IPAddress.Loopback, port);
            })
                      .CreateClient((name, services) =>
            {
                services.AddTcpIpcClient <ITestService>(name, IPAddress.Loopback, port);
            });
        }
Exemple #17
0
        public async Task UnserializableInput_ThrowSerializationException(string pipeName)
        {
            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(pipeName);
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, pipeName);
            });

            await Assert.ThrowsAnyAsync <IpcSerializationException>(async() =>
            {
                await client.InvokeAsync(x => x.UnserializableInput(UnserializableObject.Create()));
            });
        }
Exemple #18
0
        public AppInfo()
        {
            this.InitializeComponent();
            // register IPC clients
            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddNamedPipeIpcClient <ServiceContractInterfaces>("broker", pipeName: "pipeinternal")
                                              .BuildServiceProvider();

            // resolve IPC client factory
            IIpcClientFactory <ServiceContractInterfaces> clientFactory = serviceProvider
                                                                          .GetRequiredService <IIpcClientFactory <ServiceContractInterfaces> >();

            // create client
            this.client = clientFactory.CreateClient("broker");


            DataContext = new BackgroundServiceSettingsViewModel();
            Ping();
        }
Exemple #19
0
        public AddCommandDialog()
        {
            this.InitializeComponent();
            DataContext                 = new AddCommandViewModel();
            this.comboBox               = this.FindControl <ComboBox>("ComboBox");
            this.comboBox.Items         = Enum.GetValues(typeof(AvailableCommands)).Cast <AvailableCommands>().OrderBy(v => v.ToString());
            this.comboBox.SelectedIndex = 0;

            // register IPC clients
            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddNamedPipeIpcClient <ServiceContractInterfaces>("addCommand", pipeName: "pipeinternal")
                                              .BuildServiceProvider();

            // resolve IPC client factory
            IIpcClientFactory <ServiceContractInterfaces> clientFactory = serviceProvider
                                                                          .GetRequiredService <IIpcClientFactory <ServiceContractInterfaces> >();

            // create client
            this.client = clientFactory.CreateClient("addCommand");
        }
Exemple #20
0
        public async Task MultipleEndpoints(
            Mock <ITestService> service1,
            Mock <ITestService2> service2)
        {
            IHost host = Host.CreateDefaultBuilder()
                         .ConfigureServices(services =>
            {
                services
                .AddScoped(x => service1.Object)
                .AddScoped(x => service2.Object);
            })
                         .ConfigureIpcHost(builder =>
            {
                builder
                .AddNamedPipeEndpoint <ITestService>("pipe1")
                .AddNamedPipeEndpoint <ITestService2>("pipe2");
            })
                         .Build();

            await host.StartAsync();

            ServiceProvider clientServiceProvider = new ServiceCollection()
                                                    .AddNamedPipeIpcClient <ITestService>("client1", "pipe1")
                                                    .AddNamedPipeIpcClient <ITestService2>("client2", "pipe2")
                                                    .BuildServiceProvider();

            IIpcClient <ITestService> client1 = clientServiceProvider
                                                .GetRequiredService <IIpcClientFactory <ITestService> >()
                                                .CreateClient("client1");

            await client1.InvokeAsync(x => x.ReturnVoid());

            service1.Verify(x => x.ReturnVoid(), Times.Once);

            IIpcClient <ITestService2> client2 = clientServiceProvider
                                                 .GetRequiredService <IIpcClientFactory <ITestService2> >()
                                                 .CreateClient("client2");
            await client2.InvokeAsync(x => x.SomeMethod());

            service2.Verify(x => x.SomeMethod(), Times.Once);
        }
Exemple #21
0
        public async Task ServerIsOff_Timeout()
        {
            int timeout = 1000; // 1s
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName          = "inexisted-pipe";
                    options.ConnectionTimeout = timeout;
                });
            });

            var sw = Stopwatch.StartNew();
            await Assert.ThrowsAsync <TimeoutException>(async() =>
            {
                string output = await client.InvokeAsync(x => x.StringType("abc"));
            });

            Assert.True(sw.ElapsedMilliseconds < timeout * 2); // makesure timeout works with marge
        }
        public CommandSettings()
        {
            this.InitializeComponent();
            // register IPC clients
            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddNamedPipeIpcClient <ServiceContractInterfaces>("commands", pipeName: "pipeinternal")
                                              .BuildServiceProvider();

            // resolve IPC client factory
            IIpcClientFactory <ServiceContractInterfaces> clientFactory = serviceProvider
                                                                          .GetRequiredService <IIpcClientFactory <ServiceContractInterfaces> >();

            // create client
            this.client = clientFactory.CreateClient("commands");


            DataContext = new CommandSettingsViewModel();
            GetConfiguredCommands();

            this._dataGrid = this.FindControl <DataGrid>("Grid");
        }
        public void ConnectionCancelled_Throw()
        {
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName          = "inexisted-pipe";
                    options.ConnectionTimeout = Timeout.Infinite;
                });
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            using (var cts = new CancellationTokenSource())
            {
                Task.WaitAll(
                    Task.Run(async() =>
                {
                    await Assert.ThrowsAsync <OperationCanceledException>(async() =>
                    {
                        await client.InvokeAsync(x => x.ReturnVoid(), cts.Token);
                    });
                }),
                    Task.Run(() => cts.CancelAfter(1000)));
            }
#endif
            using (var cts = new CancellationTokenSource())
            {
                Task.WaitAll(
                    Task.Run(async() =>
                {
                    await Assert.ThrowsAsync <OperationCanceledException>(async() =>
                    {
                        var request = TestHelpers.CreateIpcRequest("ReturnVoid");
                        await client.InvokeAsync(request, cts.Token);
                    });
                }),
                    Task.Run(() => cts.CancelAfter(1000)));
            }
        }
Exemple #24
0
        public async Task ConnectionTimeout_Throw()
        {
            int timeout = 3000; // 3s
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddTcpIpcClient <ITestService>(name, (_, options) =>
                {
                    // Connect to a non-routable IP address can trigger timeout
                    options.ServerIp          = IPAddress.Parse("10.0.0.0");
                    options.ConnectionTimeout = timeout;
                });
            });

            var sw = Stopwatch.StartNew();
            await Assert.ThrowsAsync <TimeoutException>(async() =>
            {
                string output = await client.InvokeAsync(x => x.StringType("abc"));
            });

            Assert.True(sw.ElapsedMilliseconds < timeout * 2); // makesure timeout works with marge
        }
        public async Task Exception_ThrowWithoutDetails(string pipeName, string details)
        {
            _serviceMock.Setup(x => x.ThrowException())
            .Throws(new Exception(details));

            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(options =>
                {
                    options.PipeName = pipeName;
                    options.IncludeFailureDetailsInResponse = false;
                });
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName = pipeName;
                });
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            IpcFaultException actual = await Assert.ThrowsAsync <IpcFaultException>(async() =>
            {
                await client.InvokeAsync(x => x.ThrowException());
            });

            Assert.Null(actual.InnerException);
#endif

            IpcFaultException actual2 = await Assert.ThrowsAsync <IpcFaultException>(async() =>
            {
                var request = TestHelpers.CreateIpcRequest("ThrowException");
                await client.InvokeAsync(request);
            });

            Assert.Null(actual2.InnerException);
        }
Exemple #26
0
        public async Task UnserializableOutput_ThrowFaultException(string pipeName)
        {
            _serviceMock
            .Setup(x => x.UnserializableOutput())
            .Returns(UnserializableObject.Create());

            IIpcClient <ITestService> client = _factory
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(pipeName);
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, pipeName);
            });

            IpcFaultException exception = await Assert.ThrowsAnyAsync <IpcFaultException>(async() =>
            {
                await client.InvokeAsync(x => x.UnserializableOutput());
            });

            Assert.Equal(IpcStatus.InternalServerError, exception.Status);
        }
        public SimpleTypeNameContractTest(IpcApplicationFactory <ITestService> factory)
        {
            string pipeName = Guid.NewGuid().ToString();

            _client = factory
                      .WithServiceImplementation(_ => _serviceMock.Object)
                      .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(options =>
                {
                    options.PipeName = pipeName;
                    options.IncludeFailureDetailsInResponse = true;
                });
            })
                      .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.UseSimpleTypeNameAssemblyFormatHandling = true;
                    options.PipeName = pipeName;
                }
                                                              );
            });
        }
Exemple #28
0
        public void ConnectionCancelled_Throw()
        {
            IIpcClient <ITestService> client = _factory
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName          = "inexisted-pipe";
                    options.ConnectionTimeout = Timeout.Infinite;
                });
            });

            using var cts = new CancellationTokenSource();

            Task.WaitAll(
                Task.Run(async() =>
            {
                await Assert.ThrowsAsync <OperationCanceledException>(async() =>
                {
                    await client.InvokeAsync(x => x.ReturnVoid(), cts.Token);
                });
            }),
                Task.Run(() => cts.CancelAfter(1000)));
        }
Exemple #29
0
        public AddSensorDialog()
        {
            this.InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
            this.comboBox       = this.FindControl <ComboBox>("ComboBox");
            this.comboBox.Items = Enum.GetValues(typeof(AvailableSensors)).Cast <AvailableSensors>();

            // register IPC clients
            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddNamedPipeIpcClient <ServiceContractInterfaces>("addsensor", pipeName: "pipeinternal")
                                              .BuildServiceProvider();

            // resolve IPC client factory
            IIpcClientFactory <ServiceContractInterfaces> clientFactory = serviceProvider
                                                                          .GetRequiredService <IIpcClientFactory <ServiceContractInterfaces> >();

            // create client
            this.client = clientFactory.CreateClient("addsensor");


            DataContext = new AddSensorViewModel();
        }
        public async Task StreamTranslator_HappyPath(string pipeName, string input, string expected)
        {
            _serviceMock
            .Setup(x => x.StringType(input))
            .Returns(expected);

            IIpcClient <ITestService> client = _factory
                                               .WithServiceImplementation(_ => _serviceMock.Object)
                                               .WithIpcHostConfiguration(hostBuilder =>
            {
                hostBuilder.AddNamedPipeEndpoint <ITestService>(options =>
                {
                    options.PipeName         = pipeName;
                    options.StreamTranslator = x => new XorStream(x);
                });
            })
                                               .CreateClient((name, services) =>
            {
                services.AddNamedPipeIpcClient <ITestService>(name, (_, options) =>
                {
                    options.PipeName         = pipeName;
                    options.StreamTranslator = x => new XorStream(x);
                });
            });

#if !DISABLE_DYNAMIC_CODE_GENERATION
            string actual = await client.InvokeAsync(x => x.StringType(input));

            Assert.Equal(expected, actual);
#endif

            var request = TestHelpers.CreateIpcRequest(typeof(ITestService), "StringType", false, new object[] { input });
            var actual2 = await client.InvokeAsync <string>(request);

            Assert.Equal(expected, actual2);
        }